Qt QML状态states的使用

效果

状态 绿灯 黄灯 红灯
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;
            }
        }
    }
}

发布了91 篇原创文章 · 获赞 47 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/whik1194/article/details/104837441