Question

I want to create MenuItem dynamically and add onTriggered callback for it.

var m = backContextMenu.insertItem(0,text) 

m.onTriggered = ..? //function(x) { console.log('asd') }

It gives me error Cannot assign to read-only property "onTriggered". What can I do? Maybe I should create my menu using Qt.createQmlObject('qml code...')? Or maybe I should create MenuItem template declaratively and clone this object somehow?

P.S. I use MenuItem from QtQuick.Controls in Qt 5.2

Was it helpful?

Solution

You can use Connections QML item to create dynamic connections using createQmlObject function :

var item = menuContext.insertItem(0, "menu item")
Qt.createQmlObject("import QtQuick 2.0;Connections{onTriggered:foo()}",item)

Simply, you can create also direct connection :

item.onTriggered.connect(foo)

(MenuItem is necessarily Qt Quick 2 and Qt 5.1)

OTHER TIPS

I was lucky to find another way to add Menu items dynamically: via Instantiator.

Menu {
    id: recentFilesMenu

    Instantiator {
        model: recentFilesModel
        MenuItem {
            text: model.fileName
        }
        onObjectAdded: recentFilesMenu.insertItem(index, object)
        onObjectRemoved: recentFilesMenu.removeItem(object)
    }

    MenuSeparator {
        visible: recentFilesModel.count > 0
    }

    MenuItem {
        text: "Clear menu"
        enabled: recentFilesModel.count > 0
        onTriggered: recentFilesModel.clear()
    }
}

Sample code will explain everything:

    Menu {
        id: suggestionsMenu
        property var suggestions: []

        Instantiator {
            model: suggestionsMenu.suggestions
            onObjectAdded: suggestionsMenu.insertItem(index, object)
            onObjectRemoved: suggestionsMenu.removeItem(object)
            delegate: MenuItem {
                text: suggestionsMenu.suggestions[index]
                onTriggered: {
                    console.log(index + " : " + suggestionsMenu.suggestions[index])
                }
            }
        }
    }

Now in code you only need to call such 3 lines:

onShowSuggestions: {
   console.log("Showing suggestions")
   console.log(suggestions)

   suggestionsMenu.clear()
   suggestionsMenu.suggestions = []
   suggestionsMenu.suggestions = suggestions
   suggestionsMenu.popup()
}

Links:

Menu QML

Instantiator QML Type

Article #1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top