属性绑定
属性绑定是QML的核心功能,可让开发人员指定不同对象属性之间的关系。当属性的依赖项的值更改时,该属性将根据指定的关系自动更新。
Rectangle {
width: 200; height: 200
Rectangle {
width: 100
height: parent.height //蓝色矩形绑定了父矩形的高度,当父矩形高度变化时,蓝色矩形也变化
color: "blue"
}
}
绑定可以包含任何有效的JavaScript表达式或语句,因为QML使用符合标准的JavaScript引擎。绑定可以访问对象属性,调用方法并使用内置的JavaScript对象(例如Date
和)Math
。
height: parent.height / 2 //绑定js表达式
height: Math.min(parent.width, parent.height) //调用js函数
height: parent.height > 100 ? parent.height : parent.height/2 //js语句
height: {
if (parent.height > 100) //js代码
return parent.height
else
return parent.height / 2
}
height: someMethodThatReturnsHeight() //js 自定义函数
下面是一个涉及更多对象和类型的更复杂的示例:
Column {
id: column
width: 200
height: 200
Rectangle {
id: topRect
width: Math.max(bottomRect.width, parent.width/2) //绑定
height: (parent.height / 3) + 10 //属性绑定
color: "yellow"
TextInput {
id: myTextInput
text: "Hello QML!"
}
}
Rectangle {
id: bottomRect
width: 100
height: 50
color: myTextInput.text.length <= 10 ? "red" : "blue"
}
}
从JavaScript创建属性绑定
具有绑定的属性会根据需要自动更新。但是,如果以后从JavaScript语句为属性分配了静态值,则绑定将被删除。
import QtQuick 2.0
Rectangle {
width: 100
height: width * 2
focus: true
Keys.onSpacePressed: {
height = width * 3 //按下空格后,js给height赋值,动态绑定将失效
}
}
//如果还想继续属性绑定的话,可使用Qt.binding来重新绑定
import QtQuick 2.0
Rectangle {
width: 100
height: width * 2
focus: true
Keys.onSpacePressed: {
height = Qt.binding(function() { return width * 3 }) //重新绑定
}
}
调试属性绑定
QML应用程序中错误的常见原因是意外地用JavaScript语句中的静态值覆盖了绑定。为了帮助开发人员查找此类问题,QML引擎能够在由于强制性分配而导致绑定丢失时发出消息。
为了生成此类消息,您需要启用qt.qml.binding.removal
日志记录类别的信息输出
QLoggingCategory::setFilterRules(QStringLiteral("qt.qml.binding.removal.info=true"));
属性绑定时使用this
使用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指的是item
console.log("rect.height = " + rect.height) // prints 200, not 1000
}
}