为什么 属性 QML 中的绑定更改不会立即传播

Why does property binding change in QML not propagate immediately

在 QML 中应用 属性 绑定时,我遇到了一个问题。当我们有一个 parent 组件(Window)和一个 child(矩形)时,它有一些属性绑定到 parent 的(宽度、高度或 anchors.fill: parent),当我在 JS 代码中更改 parents 属性时,如果我想读取 child 属性的值(绑定到 parent's) 在相同的 JS 代码中,它显示旧值(未更新)。 parent 的属性更改似乎尚未传播到 child 的属性。这是此问题的示例:

Window {
id:myWindow
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle{
    id:customRec
    width:parent.width
    height: parent.height
    color: "blue"
}
Button{
    id:myBtn
    onClicked: {
        myWindow.width = 800
        myWindow.height = 600
        console.log(customRec.width)
        console.log(customRec.height)
    }
}}

点击按钮后,显示: 质量毫升:640 质量毫升:480 而不是 800 和 600,新值。虽然矩形已经很好地缩放了。再次单击后,它将显示更新后的值(800 和 600)。有人可以解释这里发生了什么,以及绑定 属性 更改如何立即传播到绑定属性。我正在使用带有 msvc2017_64 编译器的 Qt 5.12.2。

您正在打印更新前的属性。使用以下代码,您可以发现 onWidthChanged 信号出现在控制台日志之后。 onWidthChanged信号在更新宽度后出现。

import QtQuick 2.10
import QtQuick.Window 2.10
import QtQuick.Controls 2.2

Window {
    id:myWindow
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Rectangle{
        id:customRec
        width: parent.width
        height: parent.height
        color: "blue"
        onWidthChanged: console.log("***********")
    }
       Button{
        id:myBtn
        width: 100
        height: 100

        onClicked: {
            myWindow.width = myWindow.width +50
            myWindow.height = myWindow.height +50
            console.log("--------------------------")
            console.log("window width" + myWindow.width)
            console.log("window height" + myWindow.height)
            console.log("customrect width" + customRec.width)
            console.log("customrect height" + customRec.height)
        }
    }

}