3

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

pourjour
  • 1,186
  • 2
  • 13
  • 28

2 Answers2

6

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)
   }
}
Mitch
  • 23,716
  • 9
  • 83
  • 122
pourjour
  • 1,186
  • 2
  • 13
  • 28
  • 3
    Please add the following information to your question (both as import and as tag) - Which version do you use for your QtQuick.Controls? Is it `QtQuick.Controls 1.x` (tag: `qtquickcontrols`) or `QtQuick.Controls 2.x` (tag: qtquickcontrols2) – derM - not here for BOT dreams Aug 14 '17 at 07:31
1

You just need to add the text for every single ListElement to your MenuItem like this:

Menu{
    id:contextMenu
    visible: true
    Repeater {
        model: menuItems
        MenuItem {
            text: modelData
        }
    }
}

I also added "visible: true" to your Menu to show it(I dont know if you are opening it somewhere else).

0x90
  • 61
  • 3
  • Do you get any errors? Does the Menu show up or is the Menu filled with empty entries? The answer was tested with Qt 5.9.0 – 0x90 Aug 12 '17 at 17:40
  • I'm using Qt 5.9.1, but no errors are shown. the menu just not displaying – pourjour Aug 12 '17 at 17:43
  • However I figured out how to do it from documentation, I've posted an answer – pourjour Aug 12 '17 at 17:43
  • If the version used is `QtQuick.Controls 2.x` you need to insert the two lines: `onItemAdded: contextMenu.insertItem(index, item)` and `onItemRemoved: contextMenu.removeItem(item)`. In the older version, `MenuItem` is no `Item` – derM - not here for BOT dreams Aug 14 '17 at 07:41