繁体   English   中英

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

[英]Why does property binding change in QML not propagate immediately

在 QML 中应用属性绑定时,我遇到了一个问题。 当我们有一个父组件(Window)和一个子组件(Rectangle),它有一些属性绑定到父组件(宽度、高度或 anchors.fill: parent),当我在 JS 代码中更改父组件属性时,如果我想在相同的 JS 代码中读取子属性(绑定到父属性)的值,它显示旧值(未更新)。 看起来父属性的更改尚未传播到孩子的。 下面是这个问题的例子:

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)
    }
}}

单击按钮后,它显示: qml: 640 qml: 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)
        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM