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”状态包含了一组相对于隐式默认状态(即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 }
}
}由于我们不希望文本瞬间出现在底部,而是希望它平滑移动,因此我们在两个状态之间添加了一个过渡效果。
from to 定义了过渡将运行的两个状态。在此情况下,我们希望从默认状态过渡到“下”状态。
由于我们希望从“下拉”状态切换回“默认”状态时,该过渡效果能以相反方向运行,因此将reversible 设置为true 。这相当于分别编写这两个过渡效果。
ParallelAnimation 类型可确保两种动画(数值和颜色)同时开始。我们也可以使用SequentialAnimation 来让它们依次运行。
有关状态和过渡的更多详细信息,请参阅《Qt Quick 状态》以及“状态与过渡”示例。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.