QML 中的属性绑定
有两种方法可以给 QML 对象的属性进行赋值:静态值和绑定值。
例如 height: 100,这是一个静态值。然而 height: width * 2,这就是一个绑定值。绑定值表示属性的值跟将随绑定表达式计算出来的值。这里表示的是高永远是宽的两倍。
运用绑定表达式给对象赋值也就是常说的属性绑定(Property Binding),它是 QML 中的一个核心特性。
一、使用冒号
以冒号表示的属性绑定是最常见的属性绑定方法。冒号后面的可以是任意 JS 表达式或者语句、QML 对象属性、函数调用以及 JS 中的内置对象,比如 Date、Math 等。
// 动态绑定示例
height: parent.height / 2
height: Math.min(parent.width, parent.height)
height: parent.height > 100 ? parent.height : parent.height / 2
height: {
if (parent.height > 100)
return parent.height
else
return parent.height / 2
}
height: someMethodThatReturnsHeight()
以上的属性绑定方式,如果在 JS 语句中再次指定了一个静态值,绑定将从此失效。
Rectangle {
width: 100
height: width * 2
focus: true
Keys.onSpacePressed: {
height = width * 3 // 按下空格键后,height 的值将不再随 width 的变化而变化
}
}
但可以重新绑定,方法是使用 Qt.binding(function) 。
二、Qt.binding(function) 方法
Rectangle {
width: 100
height: width * 2
focus: true
Keys.onSpacePressed: {
height = Qt.binding(function() { return width * 3 }) // 重新绑定
}
}
在 JS 函数中进行属性绑定时,还可以使用 this 关键字,它代表接收这个绑定的对象。
Item {
width: 500
height: 500
Rectangle {
id: rect
width: 100
color: "yellow"
}
Component.onCompleted: {
rect.height = Qt.binding(function() { return this.width * 2 }) // this 代表的是 rect
console.log("rect.height = " + rect.height) // prints 200, not 1000
}
}
另外一种属性绑定的绑定方法是:运用 QML 中的 Binding 类型。
三、Binding 类型
Binding 主要提供两种能力:
-
绑定到不可访问的属性
// app 是 C++ 中导出的属性,在 QML 中不可直接进行属性绑定,但可用 Binding 进行绑定 TextEdit { id: myTextField; text: "Please type here..." } Binding { target: app; property: "enteredText"; value: myTextField.text } -
条件绑定
Binding 可以通过 delay 设置延时绑定:不会立即更新被绑定的对象,要等到事件队列空闲的时候再去响应。
Binding 可以通过 when 指定何种条件下才去响应。
总结
QML 中的属性绑定有三种方法:
-
QML 对象初始化时用冒号绑定
能在对象初始化时绑定,不能在运行时绑定
-
运行时在 JS 函数中用 Qt.binding() 方法绑定
不能在初始化时绑定,能在运行时绑定
-
Binding 类型进行绑定
能给不可访问的属性进行绑定,可以设置条件绑定
参考
https://doc.qt.io/qt-5/qtqml-syntax-objectattributes.html
https://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html
QML中的属性绑定可通过冒号、Qt.binding()方法和Binding类型实现。冒号绑定适用于对象初始化,Qt.binding()用于运行时,Binding类型支持不可访问属性和条件绑定。详细介绍了这三种方法的使用和特点。
515

被折叠的 条评论
为什么被折叠?



