QML教程3 - 状态与转换

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

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

以下是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状态包括从我们的隐式default状态(QML中最初定义的项目)到一系列属性更改。具体来说,我们将文本的translate="no">y属性设置为translate="no">160,旋转设置为translate="no">180,并将translate="no">color设置为红色。

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

由于我们不想让文本立即出现在底部,而是希望它平滑移动,我们在两种状态之间添加了一个转换。

translate="no">fromtranslate="no">to定义了转换将在两种状态之间运行。在这种情况下,我们希望在默认状态到我们的down状态之间进行转换。

因为我们希望在从down状态回到默认状态时,同一种转换倒退运行,所以我们把translate="no">reversible设置为translate="no">true。这相当于单独写下两种转换。

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

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

© 2024 Qt Company Ltd. 本文档中的文档贡献的版权属于各自的拥有者。本提供在此的文档是根据自由软件基金会发布的GNU自由文档许可证版本1.3的条款颁发的。Qt和相应的标志是芬兰和/或其他国家的Qt Company Ltd.的商标。所有其他商标均为各自所有者的财产。