QML state详解

1.state简介

changes(list<Change>):保存当前State下的多个Change对象,比如PropertyChanges、StateChangeScript、ParentChange等。
extend(string):表示该状态要在哪个State的基础上进行扩展,当一个状态要在另一个状态基础上进行扩展时,它将继承该另一个状态的所有changes。
name (string ):此属性保存状态的名称,每个状态在其项目内应具有唯一的名称。
when(bool ):该属性在应用状态成立时生效。应该将其设置为一个表达式,您希望何时应用状态时使该表达式的计算结果为true。

当一个对象的状态发生改变,那么该对象展示给用户的效果也会相应发生改变,所以state支持了多个不同change对象供我们使用,有如下几种:

  • PropertyChanges: 改变对象的属性值
  • StateChangeScript:运行脚本,比如function函数
  • ParentChange: 改变对象的父类对象.并且改变对象在父类对象下的坐标xy,宽高等属性
  • AnchorChanges: 改变对象的anchor值

2.示例

示例1:定义了两种状态,Rectangle中,鼠标按下时显示pressed状态,松开鼠标时显示released状态。

Window {
    visible: true
    width: 400
    height: 400
    title: qsTr("Hello World")

    Rectangle  {
        id: rect
        width:  100
        height:  100
        state: "pressed";
        MouseArea  {
            id:  mouseArea
            anchors.fill:  parent
            onPressed: {
                rect.state = "pressed";
            }
            onReleased: {
                rect.state = "released";
            }
        }

        states:  [
            State  {
                name:  "pressed"
                PropertyChanges  {
                    target:  rect;
                    color:  "red"
                }
            },
            State  {
                name:  "released"
                PropertyChanges  {
                    target:  rect;
                    color:  "yellow"
                }
            }
        ]
    }
}

示例2:鼠标按下的时候,rect隐藏。

Window {
    visible: true
    width: 400
    height: 400
    title: qsTr("Hello World")

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

        MouseArea {
            id:  mouseArea
            anchors.fill:  parent
        }

        states:
            State {
            name:  "hidden"
            when:  mouseArea.pressed
            PropertyChanges {
                target:  rect
                opacity:  0
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/wzz953200463/article/details/129226860
QML