【问题标题】:How to call QML Menu::addMenu without warnings?如何在没有警告的情况下调用 QML Menu::addMenu?
【发布时间】:2015-08-12 08:34:36
【问题描述】:

我想动态构建一个 QML 上下文菜单。 当我调用“addMenu”时,会添加菜单条目,但我收到此警告:

QQmlComponent: 创建的图形对象没有放在图形场景中。

这里是重现问题的代码:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

ApplicationWindow {
    title: qsTr("Hello World")
    width: 640
    height: 480

    Menu {
        id:contextMenu
    }

    MouseArea {
        anchors.fill: parent
        acceptedButtons: Qt.RightButton
        onClicked: {
            contextMenu.addMenu("NewMenu");
            contextMenu.popup();
        }
    }
}

我在这里做错了什么?

【问题讨论】:

  • 它适用于 5.5 没有警告,所以也许你只需要更新。
  • 就像说@folibis 在 5.5 上没有警告,试试这个也许会更好contextMenu.insertMenu(contextMenu.__currentIndex,"NewMenu")
  • 谢谢@folibis,我会更新的。

标签: qt qml qtquick2 qt5.4


【解决方案1】:

对我来说,这看起来像是 Qt 中的一个错误。如果您查看Menu.qml(其中定义了Menu QML 组件),addMenu 的定义如下:

function addMenu(title) {
    return root.insertMenu(items.length, title)
}

function insertMenu(index, title) {
    if (!__selfComponent)
        __selfComponent = Qt.createComponent("Menu.qml", root)
    var submenu = __selfComponent.createObject(__selfComponent, { "title": title })
    root.insertItem(index, submenu)
    return submenu
}

/*! \internal */
property Component __selfComponent: null

这里重要的一行是__selfComponent.createObject(__selfComponent, { "title": title })。这会将__selfComponent(菜单组件,而不是菜单本身)设置为新创建的子菜单的父级。我认为这是错误的,应该将父级设置为root,即菜单本身。

【讨论】:

    【解决方案2】:

    像这样将visible: true 添加到ApplicationWindow

    ApplicationWindow {
        title: qsTr("Hello World")
        width: 640
        height: 480
        visible: true
        Menu {
            id:contextMenu
        }
    ...
    

    也许有帮助。

    【讨论】:

      猜你喜欢
      • 2013-12-22
      • 2021-11-22
      • 2017-10-29
      • 2019-05-14
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多