states : list<State>:Item元素状态

在states对象中列出元素可能会处于的状态,再依据条件进行修改item的state属性即可实现item状态的动态更改,例如:鼠标按下是显示红色,松开时显示蓝色默认状态是绿色,这里是直接调用PropertyChanges()方法进行的设置,指定操作元素target,与需要修改的属性和对应的修改值即可立即进行修改。

  1. Rectangle {
  2. id: root
  3. width: 100; height: 100
  4. state: "normal"
  5. states: [
  6. State {
  7. name: "normal"
  8. PropertyChanges { target: root; color: "green" width200}
  9. },
  10. State {
  11. name: "red_color"
  12. PropertyChanges { target: root; color: "red" width150}
  13. },
  14. State {
  15. name: "blue_color"
  16. PropertyChanges { target: root; color: "blue" }
  17. }
  18. ]
  19. MouseArea{
  20. anchors.fill: parent
  21. // onClicked: { //在鼠标区域内进行点击操作即可触发,不需focus设置true
  22. // console.log("on clicked")
  23. // root.state = "red_color"
  24. // }
  25. onPressed: { //在鼠标区域内进行点击操作即可触发,不需focus设置true
  26. console.log("on Pressed")
  27. root.state = "red_color"
  28. }
  29. onReleased: {
  30. console.log("on Released"
  31. root.state = "blue_color"
  32. }
  33. }
  34. }

transitions : list

上述例子中实现了元素的动态切换,状态的切换是立即切换的效果,没有一个渐变效果,搭配使用transitions,在元素从一个状态到另一个状态的过程中设置一个动画效果。

  1. Rectangle {
  2. width: 75; height: 75
  3. id: button
  4. state: "RELEASED"
  5. MouseArea {
  6. anchors.fill: parent
  7. onPressed: button.state = "PRESSED" //当需要状态直接切换的时候世界使用state修改,如果需要一个过度动作就结合transitions配合
  8. onReleased: button.state = "RELEASED"
  9. }
  10. states: [
  11. State {
  12. name: "PRESSED"
  13. PropertyChanges { target: button; color: "red"}
  14. },
  15. State {
  16. name: "RELEASED"
  17. PropertyChanges { target: button; color: "green"}
  18. }
  19. ]
  20. transitions: [ //状态过度动画
  21. Transition {
  22. from: "PRESSED"
  23. to: "RELEASED"
  24. ColorAnimation {
  25. target: button;
  26. // to: "red"
  27. duration: 200
  28. }
  29. },
  30. Transition {
  31. from: "RELEASED"
  32. to: "PRESSED"
  33. ColorAnimation { target: button; duration: 500}
  34. }
  35. ]
  36. }

当鼠标按下时,设备状态是pressed,调用按下状态,颜色属性改变,transitions中定义了release到pressed时颜色动画的持续时间,经过验证,不可在颜色动画中指定要调整到的颜色,显示的颜色会进行错误的变化。