QML 中的状态

Qt hello – 专注于Qt的技术分享平台

状态描述了当前用户界面样子,QML中一个状态定义了一组属性的改变,并且会在一定条件下被触发。

假设有这么一个场景,红黄绿三个灯,用一个按钮,点击后依次切换三个灯亮起。使用QWidget的思路去实现就是在按钮click对应的槽函数中,依次获取三个button的指针,然后改变其颜色,这样也能实现,但是不够优雅。QML的思路是,全局定义一组状态,然后每个状态来控制具体的属性,使用时只要切换不同状态就可以了,后续修改的话,只需要修改这个全局状态就行,并且三个按钮集中暴露在这组状态中。

一,定义三个灯

//三个灯的按钮
    Row{
        anchors.centerIn: parent
        spacing: 20
        //红灯
        Rectangle{
            id:red
            width: 50
            height: 50
            radius: 50
            color: "red"
        }

        //黄灯
        Rectangle{
            id:yellow
            width: 50
            height: 50
            radius: 50
            color: "yellow"
        }

        //绿灯
        Rectangle{
            id:green
            width: 50
            height: 50
            radius: 50
            color: "green"
        }
    }

二,定义一组状态,每个状态控制 三个灯具体的属性

//定义一组状态 规定每个状态下 的属性
    Item{
        id:root
        state:"red"
        states: [
            State {
                //红灯状态 红灯亮 其它灭
                name: "red"
                PropertyChanges {target: red;color:"red"}
                PropertyChanges {target: yellow;color:"gray"}
                PropertyChanges {target: green;color:"gray"}
            },
            State {
                name: "yellow"
                PropertyChanges {target: yellow;color:"yellow"}
                PropertyChanges {target: red;color:"gray"}
                PropertyChanges {target: green;color:"gray"}
            },
            State {
                name: "green"
                PropertyChanges {target: green;color:"green"}
                PropertyChanges {target: red;color:"gray"}
                PropertyChanges {target: yellow;color:"gray"}
            }
        ]
    }

三,切换时 只需要指定 当前状态是 谁即可。

//依次切换三个状态
    Button{
        anchors.bottom: parent.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        text: qsTr("切换")
        onClicked: {
            if(root.state=="red")
                root.state="yellow"
            else if(root.state=="yellow")
                root.state="green"
            else
                root.state="red"
        }
    }

四,效果

五,过渡

 移步到这里:QML 中的状态 – Qt hello

  • 15
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

土拨鼠不是老鼠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值