源于群友的提问,以前项目中也遇到过的问题,最后在Qml帮助文档找到的解决方法。
下面代码中,Text对象绑定了car.wheels
属性。当onCompleted
执行完成时,car.wheels = 6
也同样执行完成了。预想结果是Text对象会动态更新,但实际上是不会更新的。
Item {
property var car: new Object({wheels: 4})
Text {
text: "The car has " car.wheels " wheels";
}
Component.onCompleted: {
car.wheels = 6;
}
}
让我们看看Qml文档是如何描述的吧:
代码语言:javascript复制It is important to note that changes in regular properties of JavaScript objects assigned to a var property will not trigger updates of bindings that access them.
The example below will display "The car has 4 wheels" as the change to the wheels property will not cause the reevaluation of the binding assigned to the "text" property:
重要注意,
分配给var属性的JavaScript对象的常规属性中的更改不会触发访问它们的绑定的更新。
下面的示例将显示"The car has 4 wheels",
因为车轮属性的更改不会导致重新求值分配给“文本”属性的绑定
那么我想更新Text对象呢,怎么更新呢?帮助文档同样也给出答案,就是更新整个car
的属性:
If the onCompleted handler instead had "car = new Object({wheels: 6})" then the text would be updated to say "The car has 6 wheels",
since the car property itself would be changed, which causes a change notification to be emitted.
如果onCompleted处理程序具有 "car = new Object({wheels: 6})",
则该文本将更新为"The car has 6 wheels",
因为car属性本身将被更改,
这将导致更改通知被发射。
文档引用: https://doc.qt.io/qt-5/qml-var.html#change-notification-semantics