QML使用state示例

本文采用两种方式实现按钮悬浮、按下时背景变化效果,用于介绍state使用方法。

1、采用事件区分各场景颜色

Button {
    id:mainBtn

    background: Rectangle{
        color: mainBtn.pressed ? "#9d9d9d" : mainBtn.hovered ? "#009688" : "#f0f0f0"
        border.width: (mainBtn.pressed || mainBtn.hovered) ? 1 : 0
        border.color: mainBtn.pressed ? "red" : mainBtn.hovered ? "yellow" : "#f0f0f0"
    }
}

2、采用state方式设定各场景颜色

Button {
    id:mainBtn

    background: Rectangle{
        id:bgRect
        color: "#f0f0f0"
    }

    state: "normal"

    states:[
        State{
            name: "normal"
            PropertyChanges {
                target: bgRect
                color: "#f0f0f0"
                border.width: 0
                border.color: "#f0f0f0"
            }
        },
        State{
            name: "pressed"
            PropertyChanges {
                target: bgRect
                color: "#9d9d9d"
                border.width: 2
                border.color: "red"
            }
        },
        State{
            name: "hovered"
            PropertyChanges {
                target: bgRect
                color: "#009688"
                border.width: 1
                border.color: "yellow"
            }
        }

    ]
    MouseArea{
        anchors.fill: parent
        hoverEnabled: true
        onEntered: {
            mainBtn.state = "hovered"
        }
        onPressed: {
            if (pressed)
                mainBtn.state = "pressed"
        }
        onExited: {
            mainBtn.state = "normal"
        }
        onClicked: {
            mainBtn.clicked();
        }
    }
}

3、state用法

1、定义状态
一个状态的定义可以声明为states:State{...},也可以声明为:states:[State{...}]。
多个状态声明:states:[
States{...}, //状态1
States{...}, //状态2
...
]
2、状态名称
每个state需要定义一个唯一的名称。
3、绑定目标
对于State,需要定义一个或多个PropertyChanges
PropertyChanges需要一个target,用于绑定qml对象。如:
states:State{
name: "test" when: mouseArea.pressed
target: idRect
color: "cyan"
}
4、触发状态改变
有两种方式触发状态的改变:
1.在State中定义一个when,当发生该事件时触发当前状态。如when:mouseArea.pressed,当单击按下时触发
2.主动改变在定义states的空间的state属性,该属性在item中定义,因此只要在控件类型继承自Item的都存在这个属性。如下
idRect.state = "normal"
idRect.state = "pressed"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值