Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add Menu in MenuBar of ApplicationWindow in QML

Tags:

qt

qml

I'm trying to create an application that is extensible with plugins. Now the plugins should be able to add a Menu dynamically in the MenuBar.

From documentation I can find a MenuBar that is provided by QtLabsPlatform. This has a method addMenu. But Windows was not in the list of supported platforms. So I cannot benefit from it.

I tried the placeholder technique suggested in Error adding a Menu in QML, but this does not work with QtQuick.Controls 2.13

like image 240
Logesh G Avatar asked Oct 02 '19 08:10

Logesh G


1 Answers

In the @timday answer in the question you indicate indicates the answer but does not show an example:

... Dynamic creation of Menus is a little harder; see Qt.createQmlObject or Qt.createComponent docs. (It may be simpler to just declare all the ones you need in your code, but with their visible property wired to whatever logic is appropriate). ...

(emphasis mine)

So my answer is just to show you how to do it although I think you want to add MenuItem to a Menu dynamically, instead of a Menu to a MenuBar:

import QtQuick 2.13
import QtQuick.Controls 2.13


ApplicationWindow {
    id: root
    width: 640
    height: 480
    visible: true
    menuBar: MenuBar {
        Menu {
            id: plugins_menu
            title: qsTr("&Plugins")   
        }
    }
    function onTriggered(item){
        console.log(item.text)
    }
    Component.onCompleted:{
        var plugin_names = ["plugin1", "plugin2", "plugin3"]
        for(var i in plugin_names){
            var item = Qt.createQmlObject('import QtQuick 2.13; import QtQuick.Controls 2.13; MenuItem {}',
                                       plugins_menu)
            item.text = plugin_names[i]
            plugins_menu.addItem(item)
            var f = function(it){ 
                it.triggered.connect(function (){ root.onTriggered(it)
            })}
            f(item)
        }
    }
}
like image 200
eyllanesc Avatar answered Nov 17 '22 11:11

eyllanesc