qtqmlqtquickcontrols

QML - Filling menu with model items


I'm trying to fill a Menu dynamically from a ListModel, but this approach won't work (when I right click the menu won't show anything):

this my menuItems:

import QtQuick.Controls 1.3

ListModel{
    id:menuItems
    ListElement{
        text:"hello1"
    }
    ListElement{
        text:"hello2"
    }
    ListElement{
        text:"hello3"
    }
}

and this my menu

Menu{
    id:contextMenu
    Repeater{
    model: menuItems
    MenuItem{}

}

I even tried to put a an Instantiator but the menu won't show anything


Solution

  • After looking in documentation I figured out how to achieve that:

    Menu {
        id: contextMenu
    
        Instantiator {
           model: menuItems
           MenuItem {
              text: model.text
           }
    
           // The trick is on those two lines
           onObjectAdded: contextMenu.insertItem(index, object)
           onObjectRemoved: contextMenu.removeItem(object)
       }
    }