【问题标题】:Why does property binding change in QML not propagate immediately为什么 QML 中的属性绑定更改不会立即传播
【发布时间】:2019-12-20 09:38:29
【问题描述】:

在 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。

【问题讨论】:

    标签: qt qml qt-quick


    【解决方案1】:

    您在属性更新之前打印它们。使用下面的代码,您可以发现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)
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-17
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多