20200312-01 QML 三種自動綁定 --包含 賦值之後不改變原先綁定

一、前言

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章