如何避免在 QML 初始化时创建属性绑定? [英] How can I avoid creating a property binding on initialization in QML?

查看:21
本文介绍了如何避免在 QML 初始化时创建属性绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有两个属性 onetwo 的自定义 QML 组件,它们在未初始化时应该具有默认值.特别是,如果 two 应该得到一个依赖于 one 的初始值.以下代码

I want to create a custom QML component with two properties one and two, which should have default values when left uninitialized. In particular, if two should get an initial value depeding on one. The following code

Rectangle {
  property int one: 1
  property int two: 2 * one
}

然而会创建一个属性绑定:每当 one 更改时,two 都会更新为 2 * one 的新值.如何在不创建绑定的情况下将 two 初始化为 2 * onevalue?

however creates a property binding: Whenever one changes, two is updated to the new value of 2 * one. How can I initialize two to the value of 2 * one without creating a binding?

推荐答案

一种明确告诉您不需要绑定的方法是在表达式块中调用赋值:

A way to explicitly tell that you don't want a binding is to call an assignment in an expression block:

Rectangle {
  property int one: 1
  property int two: {two = 2 * one}
}

与在onCompleted中打破绑定的方法不同,表达式块避免了绑定对象的创建和销毁,看起来更干净.

Unlike the approach of breaking the binding in onCompleted, the expression block avoids the creation and then destruction of a binding object, and it looks cleaner.

这篇关于如何避免在 QML 初始化时创建属性绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆