前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Qml属性绑定小误区

Qml属性绑定小误区

作者头像
Qt君
发布2023-03-17 14:49:12
4980
发布2023-03-17 14:49:12
举报
文章被收录于专栏:跟Qt君学编程跟Qt君学编程

源于群友的提问,以前项目中也遇到过的问题,最后在Qml帮助文档找到的解决方法。

  下面代码中,Text对象绑定了car.wheels属性。当onCompleted执行完成时,car.wheels = 6也同样执行完成了。预想结果是Text对象会动态更新,但实际上是不会更新的。

代码语言:javascript
复制
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的属性:

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-12-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Qt君 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档