QML-Item的state

1、Item有两个状态属性

 

 

 states用来定义Item有多少种State状态,如长、宽,x、y,颜色,字体大小等等;

 state用来指定当前Item的状态是states种的哪一个。

所以我们重点在于知道State是个啥

 

2、关于State

 

 

主要有4个属性:

①、changes:哪种变化,用的最多的是PropertyChanges,除此以外还有【不确定是不是】;

 

 

 ②、name:当前状态的名称;

 ③、when:可以切换当前状态的时机,如指定当MouseArea点击时切换到本状态;

 ④、extend:暂未了解

 

3、关于PropertyChanges

 

 

 主要有3个属性:

 ①、target:此属性绑定目标,如绑定一个Rectangle【root】,绑定后就可以在PropertyChanges里设置目标root的属性如width为多少;

 ②、explicit:设置目标某属性时,是否与目标值绑定,如设置root的width为root2的width,当explicit为true时此时两个width是动态绑定的,root2的width变化了root的跟着变;为false时只是值相等;

 ③、restoreEntryValues:条件不匹配时是否恢复状态

 

4、实例1:鼠标点击更改Text的颜色

通过我们自己写js逻辑来实现:text默认为红色,点击后在红色和蓝色之间切换,代码:

import QtQuick 2.6
import QtQuick.Window 2.2

Rectangle {

    Text {
        id:textTest
        font.pixelSize: 30
        states: [
            State {
                name: "redStates"
                PropertyChanges {
                    target: textTest
                    color:"red"
                }
            },
            State {
                name: "blueStates"
                PropertyChanges {
                    target: textTest
                    color:"blue"
                }
            }
        ]
        text: qsTr("Hello World")
        anchors.centerIn: parent
        state: "redStates"
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            textTest.state = textTest.state=="blueStates"?"redStates":"blueStates"
        }
    }
}

效果:

 

 

 如上onClicked里的就是我们去写逻辑代码匹配状态,鼠标点击一次颜色切换一次。

 

5、实例2:通过when来匹配状态

这种状态只会在when条件成立时切换状态,当when条件不匹配时恢复状态,代码:

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 }
        }
    }
}

 

 

 

 默认是红色正方形,点击后蓝色矩形,松开后恢复红色正方形。

 

posted @ 2021-12-02 23:27  朱小勇  阅读(222)  评论(0编辑  收藏  举报