本文采用两种方式实现按钮悬浮、按下时背景变化效果,用于介绍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"