states : list<State>:Item元素状态
在states对象中列出元素可能会处于的状态,再依据条件进行修改item的state属性即可实现item状态的动态更改,例如:鼠标按下是显示红色,松开时显示蓝色默认状态是绿色,这里是直接调用PropertyChanges()方法进行的设置,指定操作元素target,与需要修改的属性和对应的修改值即可立即进行修改。
Rectangle {
id: root
width: 100; height: 100
state: "normal"
states: [
State {
name: "normal"
PropertyChanges { target: root; color: "green" , width:200}
},
State {
name: "red_color"
PropertyChanges { target: root; color: "red" , width:150}
},
State {
name: "blue_color"
PropertyChanges { target: root; color: "blue" }
}
]
MouseArea{
anchors.fill: parent
// onClicked: { //在鼠标区域内进行点击操作即可触发,不需focus设置true
// console.log("on clicked")
// root.state = "red_color"
// }
onPressed: { //在鼠标区域内进行点击操作即可触发,不需focus设置true
console.log("on Pressed")
root.state = "red_color"
}
onReleased: {
console.log("on Released"
root.state = "blue_color"
}
}
}
transitions : list
上述例子中实现了元素的动态切换,状态的切换是立即切换的效果,没有一个渐变效果,搭配使用transitions,在元素从一个状态到另一个状态的过程中设置一个动画效果。
Rectangle {
width: 75; height: 75
id: button
state: "RELEASED"
MouseArea {
anchors.fill: parent
onPressed: button.state = "PRESSED" //当需要状态直接切换的时候世界使用state修改,如果需要一个过度动作就结合transitions配合
onReleased: button.state = "RELEASED"
}
states: [
State {
name: "PRESSED"
PropertyChanges { target: button; color: "red"}
},
State {
name: "RELEASED"
PropertyChanges { target: button; color: "green"}
}
]
transitions: [ //状态过度动画
Transition {
from: "PRESSED"
to: "RELEASED"
ColorAnimation {
target: button;
// to: "red"
duration: 200
}
},
Transition {
from: "RELEASED"
to: "PRESSED"
ColorAnimation { target: button; duration: 500}
}
]
}
当鼠标按下时,设备状态是pressed,调用按下状态,颜色属性改变,transitions中定义了release到pressed时颜色动画的持续时间,经过验证,不可在颜色动画中指定要调整到的颜色,显示的颜色会进行错误的变化。