首页 > 解决方案 > 如何在 QML 中使用 MenuBar.insertMenu 方法?

问题描述

我正在尝试在 QML 中创建一个动态菜单,代码如下:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

ApplicationWindow {
    id: root
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    menuBar: MenuBar {
        Menu {
            title: "FIRST"
        }

        Menu {
            title: "SECOND"
        }

        Menu {
            title: "THIRD"
        }
    }

    Component {
        id: myMenu

        Menu {
            title: "ZERO"
        }
    }

    Component.onCompleted: {
        var menu1 = myMenu.createObject(menuBar);
        menuBar.insertMenu(0, menu1);
    }
}

系统提示如下错误信息:

QQuickItem::stackBefore: 不能在 MenuBarItem_QMLTYPE_7(0x28607824d40) 之前堆叠 MenuBarItem_QMLTYPE_7(0x28607824d40, parent=0x28606ee4660, geometry=122,0 58x40),必须是兄弟

并且菜单的顺序是:第二、第三、第一、零。我真的不明白。为什么?

如何设置正确的菜单顺序:零、第一、第二、第三?

谢谢!

标签: qtqml

解决方案


我会说使用菜单项的可见性要容易得多

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

ApplicationWindow {
    id: root
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    menuBar: MenuBar {
        Menu {
            id: menu_zero
            title: "ZERO"
            visible: false
            //or

            visible: condition_met
        }

        Menu {
            title: "FIRST"
        }

        Menu {
            title: "SECOND"
        }

        Menu {
            title: "THIRD"
        }
    }

    Component.onCompleted: {
        if(condition_met)
            menu_zero.visible = true
    }
}

推荐阅读