一、前言
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