qml 學習要點記錄(2)

Qt.binding()的作用,動態創建新的綁定,就是向Qt.binding()傳遞一個函數來返回需要的結果。

import QtQuick 2.0

Item {
    width: 600
    height: 600
    Rectangle{
        width: 10;height: width * 2
        color: "red";anchors.centerIn: parent;focus: true
        Keys.onSpacePressed:
            /*使用Qt.binding()來綁定height和width的關係,
            * 這樣只要width變化,就是觸發height變化
            */
            height = Qt.binding(function(){return width*3})

        MouseArea{
            anchors.fill: parent
            onClicked: parent.width += 10
        }
    }
}
 

在屬性綁定中可以使用this,在其他情況下this的值都是未定義的。

connect()函數在什麼時候使用?

一般的,發射信號的QML對象類型會提供一個默認的信號處理器。但是,有時需要從一個對象發射一個信號來觸發另一個對象中定義的函數,這時就需要使用connect()函數。

關鍵屬性信號處理器Component.onCompleted:每一個QML對象都包含一個附加的Component屬性,它可以引用對象被實例化的組件。每一個Component都會發射一個onCompleted信號,其對應的onCompleted()處理器會在QML環境完全建立以後執行。在onCompleted()中的腳本代碼就可以實現在啓動時運行,一些初始化的操作都可以放在這裏進行。

一個QML文檔包含兩部分:import導入語句和一個單一的根對象聲明構成的對象樹。需要強調的時,一個QML文檔只能包含一個根對象聲明,不允許出現兩個平行的根對象。比如下面的代碼肯定是錯誤的:

import QtQuick 2.0

Item {
    width: 600
    height: 600
}

Rectangle{
    function startupFunction(){
        //...startup code
    }

    Component.onCompleted:
        startupFunction();
}
QML文件名必須以大寫字母開頭,如:Abc.qml

.qml文件中的根對象定義了可用於該QML類型的一些特性。所有屬於該根對象的屬性,信號和方法,無論是自定義聲明,還是來自QML類型,都可以在外部進行訪問,並且可以被該類型的對象進行讀取和修改。例如,在SquareButton.qml中的Rectangle使用如下代碼進行定義:

//SquareButton.qml
import QtQuick 2.0
Rectangle{
    id: root
    property bool pressed: mouseArea.pressed
    signal buttonClicked(real xPox, real yPos)

    function randomizeColor(){
        root.color =
                Qt.rgba(Math.random(), Math.random(), Math.random(), 1)
    }

    width: 100;height: 100
    color: "red"
    MouseArea{
        id:mouseArea
        anchors.fill: parent
        onClicked:
            root.buttonClicked(mouse.x, mouse.y)
    }
}
所有的SquareButton對象都可以使用這裏定義的pressed屬性、buttonClicked信號和randomizeColor()方法。例如:

//application.qml
import QtQuick 2.0
SquareButton{
    id:squareButton
    onButtonClicked:{
        console.log("Clicked", xPos, yPos)
    }
}
需要注意的時,在SquareButton.qml中定義的任何一個id值都不能在SquareButton對象中進行訪問。因爲id值只能在組件作用域進行訪問。另外,SquareButton對象也無法通過mouseArea來引用MouseArea子對象。如果想使用MouseArea等子對象中的內容,需要像這裏定義pressed屬性一樣,將子對象中的屬性定義到根對象中。如果這裏定義的SquareButton對象的id值不是squareButton,而是root,它也不會與SquareButton.qml中定義的根對象的id值發生衝突,因爲它們定義在不同的作用域。

Component組件定義只包含一個唯一的根對象,並且不能在根對象之外定義任何數據,只能使用id進行引用。Component首字母要大寫哦C,寫成componet可就是另外的意思了。

import QtQuick 2.2
Item {
    width:100;height: 100
    Component{
        id:redSquare
        Rectangle{
            color: "red"
            width: 10
            height: 10
        }
    }

    Loader{sourceComponent: redSquare}
    Loader{sourceComponent: redSquare;x:20}
}
 
 

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