QML 学习摘录 05 - 状态与过渡(states and transitions)

状态与过渡(states and transitions)

通常我们将⽤户界⾯描述为⼀种状态。⼀个状态定义了⼀组属性的改变,并且会在⼀定的条件下被触发。另外在这些状态转化的过程中可以有⼀个过渡,定义了这些属性的动画或者⼀些附加的动作。

1.状态 States

在QML中,使⽤State元素来定义状态,需要与基础元素对象(Item)的states序列属性连接。状态通过它的状态名来鉴别,由组成它的⼀系列简单的属性来改变元素。默认的状态在初始化元素属性时定义,并命名为“”(⼀个空的字符串)。

示例代码:交通信号灯有 go和stop两个状态

Item{
id:root
states: [
       State {
           name: "stop"
           PropertyChanges {target: light1;color:"red"}
           PropertyChanges {target: light2;color:"black"}
       },
       State {
           name: "go"
           PropertyChanges {target: light1;color:"black"}
           PropertyChanges {target: light2;color:"green"}
       }
   ]
}

状态的改变由由分配⼀个元素新的状态属性名来完成,如以下代码:鼠标点击时,切换状态属性名称

 MouseArea{
       anchors.fill: parent
       onClicked: parent.state = (parent.state=="stop" ? "go":"stop")
   }

2. 过渡 transitions

⼀系列的过渡能够被加⼊任何元素,⼀个过渡由状态的改变触发执⾏。你可以使⽤属性的from:和to:来定义状态改变的指定过渡。这两个属性就像⼀个过滤器,当过滤器为true时,过渡⽣效。你也可以使⽤“ ”来表⽰任何状态。例如from:”* “; to:” * ”表⽰从任⼀状态到另⼀个任⼀状态的默认值,这意味着过渡⽤于每个状态的切换。
在本节的例子中,红绿灯状态在go和stop之间切换时,利用过渡和缓冲曲线使切换过程更生动, 切换时过渡效果如下:
这里写图片描述

完成代码如下:

import QtQuick 2.3
Rectangle {
    id: root
    width: 200;height:300
    border.color: "gray"
    property int duration: 3000
   Rectangle{
       id:light1
       x:20;y:15
       width: 120;height: 120
       radius: width/2
       color: "black"
       border.color: "gray"
   }
   Rectangle{
       id:light2
       x:20;y:150
       width: 120;height: 120
       radius: width/2
       border.color: "gray"
       color: "black"
   }
    /*状态*/
   state: "stop"
   states: [
       State {
           name: "stop"
           PropertyChanges {target: light1;color:"red"}
           PropertyChanges {target: light2;color:"black"}
       },
       State {
           name: "go"
           PropertyChanges {target: light1;color:"black"}
           PropertyChanges {target: light2;color:"green"}
       }
   ]
   /*过渡*/
   transitions: [
       Transition {
           from: "stop";to: "go"
           ColorAnimation { target: light1;properties: "color";duration: 1000;easing.type: Easing.OutCirc }
           ColorAnimation { target: light2;properties: "color";duration: 1000;easing.type: Easing.OutCirc}
       },
       Transition {
           from: "go";to: "stop"
           ColorAnimation { target: light1;properties: "color";duration: 1000;easing.type: Easing.InBounce}
           ColorAnimation { target: light2;properties: "color";duration: 1000;easing.type: Easing.InBounce}
       }
   ]
   MouseArea{
       anchors.fill: parent
       onClicked: parent.state = (parent.state=="stop" ? "go":"stop")
   }
}

猜你喜欢

转载自blog.csdn.net/u010679316/article/details/78348352
今日推荐