qml屬性綁定

屬性綁定

 

屬性綁定是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
    }
}

https://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html#using-keyword-this-keyword-with-property-binding

 

 

 

 

 

 

 

發佈了17 篇原創文章 · 獲贊 0 · 訪問量 2210
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章