qtqmlqtquickcontrols2

QML - Filling menu with MenuItems from model


I need to fill the QML menu with MenuItems from the model

I found that I can do it like this:

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)
   }
}

What is described in this answer:

QML - Filling menu with model items

It partially work now, but I get an error:

Parameter "object" is not declared

And I don't understand which object I should pass to the function contextMenu.insertItem(index, object)


Solution

  • You need to pass in the parameters from the signal. Have a read Signal parameters.

    ListModel {
        id: menuItems
        ListElement { text:"hello1" }
        ListElement { text:"hello2" }
        ListElement { text:"hello3" }
    }
    
    Menu {
        id: contextMenu
        visible: true
    
        Instantiator {
           model: menuItems
    
           MenuItem {
              text: model.text
           }
    
           onObjectAdded: function(index, object) {
               contextMenu.insertItem(index, object)
           }
           onObjectRemoved: function(index, object) {
               contextMenu.removeItem(object)
           }
       }
    }