【问题标题】:Unable to set the parent of a dynamically created QML component无法设置动态创建的 QML 组件的父级
【发布时间】:2016-03-27 01:48:17
【问题描述】:

我在 QML 中创建动态组件如下:

var component = Qt.createComponent("PlayerWindow.qml")
if (component.status != component.errorString())
    console.log(component.errorString())
var playerWin = component.createObject(rootWindow);

rootWindow 是我的主应用程序窗口。现在,PlayerWindow 非常简单:

Window {
    id: playerWindow
    width: parent.width
    height: parent.height

    Component.onCompleted: {
        console.log(parent.width)
        console.log(rootWindow.height)
    }
}

问题是parent.widthrootWindow.width 的值确实不同,这在显示窗口时也很明显。但是,rootWindowcreateObject 调用中被设置为父级。所以,我不确定那里发生了什么,但我想知道这是否是在动态创建组件父组件时设置它们的正确方法。

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    尝试在代码中添加console.log(parent)。您会看到类似qml: QQuickRootItem(0x1e3e4e0) 的内容。如果您查看 Qt 文档,您会发现 Item.parent() 返回 Item 但 Windows 不是 Itemdescendant 而是 QQuickWindow。同样来自文档:

    QQuickWindow 总是有一个不可见的根项 ...

    因此,在您的情况下,parentrootWindow 是不同的对象。

    附:在您的代码中创建动态对象可能会产生错误,因为尽管Qt.createComponent 返回错误,但将执行component.createObject。只需从Qt documentation 复制代码即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-23
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2018-06-18
      • 2021-10-24
      相关资源
      最近更新 更多