飞道的博客

QML state详解

303人阅读  评论(0)

1.state简介

changes(list<Change>):保存当前State下的多个Change对象,比如PropertyChanges、StateChangeScript、ParentChange等。
extend(string):表示该状态要在哪个State的基础上进行扩展,当一个状态要在另一个状态基础上进行扩展时,它将继承该另一个状态的所有changes。
name (string ):此属性保存状态的名称,每个状态在其项目内应具有唯一的名称。
when(bool ):该属性在应用状态成立时生效。应该将其设置为一个表达式,您希望何时应用状态时使该表达式的计算结果为true。

当一个对象的状态发生改变,那么该对象展示给用户的效果也会相应发生改变,所以state支持了多个不同change对象供我们使用,有如下几种:

  • PropertyChanges: 改变对象的属性值
  • StateChangeScript:运行脚本,比如function函数
  • ParentChange: 改变对象的父类对象.并且改变对象在父类对象下的坐标xy,宽高等属性
  • AnchorChanges: 改变对象的anchor值

2.示例

示例1:定义了两种状态,Rectangle中,鼠标按下时显示pressed状态,松开鼠标时显示released状态。


  
  1. Window {
  2. visible: true
  3. width: 400
  4. height: 400
  5. title: qsTr( "Hello World")
  6. Rectangle {
  7. id: rect
  8. width: 100
  9. height: 100
  10. state: "pressed";
  11. MouseArea {
  12. id: mouseArea
  13. anchors.fill: parent
  14. onPressed: {
  15. rect.state = "pressed";
  16. }
  17. onReleased: {
  18. rect.state = "released";
  19. }
  20. }
  21. states: [
  22. State {
  23. name: "pressed"
  24. PropertyChanges {
  25. target: rect;
  26. color: "red"
  27. }
  28. },
  29. State {
  30. name: "released"
  31. PropertyChanges {
  32. target: rect;
  33. color: "yellow"
  34. }
  35. }
  36. ]
  37. }
  38. }

示例2:鼠标按下的时候,rect隐藏。


  
  1. Window {
  2. visible: true
  3. width: 400
  4. height: 400
  5. title: qsTr( "Hello World")
  6. Rectangle {
  7. id: rect
  8. width: 100
  9. height: 100
  10. color: "red"
  11. MouseArea {
  12. id: mouseArea
  13. anchors.fill: parent
  14. }
  15. states:
  16. State {
  17. name: "hidden"
  18. when: mouseArea.pressed
  19. PropertyChanges {
  20. target: rect
  21. opacity: 0
  22. }
  23. }
  24. }
  25. }


转载:https://blog.csdn.net/wzz953200463/article/details/129226860
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场