Qt QML状态states的使用

倖福魔咒の 提交于 2020-03-17 02:10:00

效果

状态 绿灯 黄灯 红灯
go
wait
stop

鼠标点击之后,依次在这三个状态循环,类似状态机原理。
在这里插入图片描述

代码

当状态改变时,去改变元素的属性。

import QtQuick 2.12
import QtQuick.Window 2.2
import QtQuick.Layouts 1.3

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

    ColumnLayout {
        id: col
        spacing: 20
        //        anchors.fill: parent
        anchors.centerIn: parent

        Rectangle {
            id: rec_green
            width: 50
            height: 50
            radius: width/2
            color: "green"
            border.color: Qt.darker(color)
        }
        Rectangle {
            id: rec_yellow
            width: 50
            height: 50
            radius: width/2
            color: "yellow"
            border.color: Qt.darker(color)
        }
        Rectangle {
            id: rec_red
            width: 50
            height: 50
            x: 100
            y: 100
            radius: width/2
            color: "red"
            border.color: Qt.darker(color)
        }
        //初始状态
        state: "go"

        //状态列表及执行的动作
        states: [
            State {
                name: "go"
                PropertyChanges {
                    target: rec_green
                    color: "green"
                }
                PropertyChanges {
                    target: rec_yellow
                    color: "black"
                }
                PropertyChanges {
                    target: rec_red
                    color: "black"
                }
            },
            State {
                name: "wait"
                PropertyChanges {
                    target: rec_green
                    color: "green"
                }
                PropertyChanges {
                    target: rec_yellow
                    color: "yellow"
                }
                PropertyChanges {
                    target: rec_red
                    color: "black"
                }
            },
            State {
                name: "stop"
                PropertyChanges {
                    target: rec_green
                    color: "black"
                }
                PropertyChanges {
                    target: rec_yellow
                    color: "black"
                }
                PropertyChanges {
                    target: rec_red
                    color: "red"
                }
            }
        ]
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            switch (col.state)
            {
            //状态跳转
            case "go":
                col.state = "wait";
                break;
            case "wait":
                col.state = "stop";
                break;
            case "stop":
                col.state = "go";
                break;
            default: break;
            }
        }
    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!