1. 程式人生 > >qml中的屬性繫結與賦值

qml中的屬性繫結與賦值

淺談qml屬性繫結與賦值

屬性賦值

就字面意思,賦一個值給屬性

Rectangle {
    id:rect
    Component.onCompeleted:{
        rect.width = 10; // 賦值
        rect.height = 10; // 賦值
        rect.color = "red"; // 賦值
    }
}

屬性賦值時會發出訊號,可以通過訊號處理器,來為訊號新增處理函式,關於訊號處理器,也就是連線到同一個訊號的槽函式的佇列,每次為訊號處理器書寫處理函式時,並不會覆蓋上一次書寫的處理器,最新的處理函式會新增到訊號處理器的處理佇列的尾部,訊號處理器被觸發時,按照佇列,先進先執行。(類似於修飾模式了)。

屬性繫結

繫結到表示式

屬性繫結可以讓屬性繫結到一個表示式,例如一個數字,一個字串,一個函式,一個運算表示式,或者一個有返回值的程式碼塊。

Rectangle {
    id:rect
    width:10 // 繫結到一個數字
    height:10 + 10 //繫結到表示式
    radius:{
        if(width > 10) return 2;
        else return 3;
    } // 繫結到一個程式碼塊
    color:Qt.rgba(1, 0.9, 0.8, 1); // 繫結到一個函式
}

通過Binding繫結屬性

Rectangle
{ id: root width: 100 height: 100 Text{ id: showText } Binding{ target:id:showText // 被繫結的物件,可以是通過c++註冊的單例物件 property:"text" // 通過字串來找到屬性 value: root.width // 繫結到root.width // Binding 相當於 // bool QObject::​setProperty(const char * name, const QVariant & value)
; }
}

通過PropertyChanges來繫結

import QtQuick 2.0

Item {
    id: container
    width: 300; height: 300

    Rectangle {
        id: rect
        width: 100; height: 100
        color: "red"

        MouseArea {
           id: mouseArea
           anchors.fill: parent
        }

        states: State {
           name: "resized"; when: mouseArea.pressed
           PropertyChanges { target: rect; color: "blue"; height: container.height }
        }
    }
}

PropertyChanges一般配合State來使用

通過Qt.binding(function)來指定一個函式來繫結到屬性

Rectangle {
    id: rect
    width: 100
    height: 100
    Component.onCompeleted: {
        width = 200; // 僅僅只是賦值操作
        height = Qt.binding( function(){
                return width*1.5;
            }); // 直接繫結到一個函式
    }
}

被繫結的表示式,內部含有物件的屬性的話,那麼每當屬性變化時,就會發生訊號,繫結表示式的屬性就會根據表示式動更新自己。