QML 通过 id 锚定到 ApplicationWindow 不起作用

2022-01-19 00:00:00 qt qml c++

我像这样测试一个简单的 QML(Qt sdk version 5.3.2) 程序

I test a simple QML(Qt sdk version 5.3.2) program like this

import QtQuick 2.3
import QtQuick.Controls 1.2

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

    Text {
        text: qsTr("Hello World")
        anchors.bottom: parent.bottom
    }
}

我希望将文本放置在应用程序窗口的底部,这是可行的.但是,如果我将 anchors.bottom: parent.bottom 更改为 anchors.bottom: appWin.bottom (通过 id),锚就不再起作用了,这是一个错误吗?

I want the text will be layed on the bottom of application window, that's work. But if I change anchors.bottom: parent.bottom to anchors.bottom: appWin.bottom (via id), anchors not work anymore, is this a bug?

推荐答案

ApplicationWindow 最终不是从 Item 派生的,所以它没有 anchors 属性,这就是为什么使用窗口的 id 不起作用的原因.那么为什么要使用parent呢?因为 you 在 ApplicationWindow 中定义的孩子变成了 中间的子代 Item 称为contentItem:

ApplicationWindow does not ultimately derive from Item, so it does not have an anchors property that's why using the window's id does not work. So why does using parent? Because the children you define in an ApplicationWindow become children of an intermediate Item called contentItem:

如果您将一个项目分配给数据列表,它将成为Window 的 contentItem,使其出现在窗口内.这几项parent 将是窗口的 contentItem,它是 Item 的根该窗口中的所有权树.... 通常不应该是必须引用 data 属性,因为它是默认属性对于 Window ,因此所有子项都会自动分配给这个属性.

If you assign an Item to the data list, it becomes a child of the Window's contentItem, so that it appears inside the window. The item's parent will be the window's contentItem, which is the root of the Item ownership tree within that Window. ... It should not generally be necessary to refer to the data property, as it is the default property for Window and thus all child items are automatically assigned to this property.

相关文章