QML 教程 3 - 状态和过渡

在本章中,我们通过引入状态和转换使这个示例变得更加动态。

我们希望文本在点击时移动到屏幕底部,旋转并变为红色。

../_images/declarative-tutorial3_animation.gif

这是QML代码:

import QtQuick

Rectangle {
    id: page
    width: 320; height: 480
    color: "lightgray"

    Text {
        id: helloText
        text: "Hello world!"
        y: 30
        anchors.horizontalCenter: page.horizontalCenter
        font.pointSize: 24; font.bold: true

        MouseArea { id: mouseArea; anchors.fill: parent }

        states: State {
            name: "down"; when: mouseArea.pressed == true
            PropertyChanges {
                helloText {
                    y: 160
                    rotation: 180
                    color: "red"
                }
            }
        }

        transitions: Transition {
            from: ""; to: "down"; reversible: true
            ParallelAnimation {
                NumberAnimation { properties: "y,rotation"; duration: 500; easing.type: Easing.InOutQuad }
                ColorAnimation { duration: 500 }
            }
        }
    }

    Grid {
        id: colorPicker
        x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4
        rows: 2; columns: 3; spacing: 3

        Cell { cellColor: "red"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "green"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "blue"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor }
        Cell { cellColor: "black"; onClicked: helloText.color = cellColor }
    }
}

演练

states: State {
    name: "down"; when: mouseArea.pressed == true
    PropertyChanges {
        helloText {
            y: 160
            rotation: 180
            color: "red"
        }
    }
}

首先,我们为文本类型创建一个新的down状态。当MouseArea被按下时,此状态将被激活,并在释放时被停用。

down 状态包括一组从我们的隐式 默认状态(QML 中最初定义的项目)的属性更改。具体来说,我们将文本的 y 属性设置为 160,旋转设置为 180,并将 color 设置为红色。

transitions: Transition {
    from: ""; to: "down"; reversible: true
    ParallelAnimation {
        NumberAnimation { properties: "y,rotation"; duration: 500; easing.type: Easing.InOutQuad }
        ColorAnimation { duration: 500 }
    }
}

因为我们不希望文本立即出现在底部,而是希望它平滑移动,所以我们在两个状态之间添加了一个过渡。

fromto 定义了过渡将运行的状态。在这种情况下,我们希望从默认状态过渡到我们的 down 状态。

因为我们希望在从down状态切换回默认状态时运行相同的反向过渡,我们将reversible设置为true。这相当于分别编写两个过渡。

ParallelAnimation 类型确保两种类型的动画(数字和颜色)同时开始。我们也可以通过使用 SequentialAnimation 来让它们依次运行。

有关状态和转换的更多详细信息,请参阅Qt Quick States状态和转换示例