一、前言
QML 内部集成 3 中绑定自动绑定的方式,2种 QML,1种 Javascript
二、正文
2.1 直接赋值
property var tValue: "xx"
Text {
id: t1
text: tValue
}
Button {
id: bt
width: 100
height: 50
onClicked: tValue += "1"
}
这样 Text 的 text 属性值就自动和 tValue 属性值绑定在一起,只要 tValue 改变则将自动写入到 Text.text 之中
优势:简单
缺点:1 无法决定何时断开链接;2 一旦重新赋值则绑定就自动改变比如t1.text = ""
那么 Text 的 text 不在与 tValue 绑定
2.2 使用 Binding
property var tValue: "xx"
Text {
id: t1
text: tValue
}
Binding {
target: t1
property: "text"
value: tValue
}
Button {
id: bt]
y: 50
width: 100
height: 50
onClicked: tValue += "1"
}
Button {
id: bt
y:100
width: 100
height: 50
onClicked: t1.text = "1"
}
binding 可以在外界自由绑定,是否恢复绑定取决 restoreMode ,还能够确定触发的条件
优势:确定触发条件,可随时启用关闭绑定,可以恢复上一次绑定或值
缺点:相对会耗费一点资源
2.3 使用 JavaScript
property var tValue: "xx"
Text {
id: t1
}
Component.onCompleted: {
t1.text = Qt.binding(function() {return tValue})
}
Button {
id: bt
width: 100
height: 50
onClicked: tValue += "1"
}
优势:可以动态改变绑定,在 Javascript 事件之中
缺点:耗费资源,尽量避免在 QML 之中使用 Javascript