第二篇中,实现了字体颜色的变化,对于 QML--学习第二篇 的文本,还可以实现“状态”和“变换”以实现动画效果。上代码:
调用函数main.cpp
#include <QtWidgets/qapplication.h>
#include <qtdeclarative/QDeclarativeview.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QDeclarativeView *m_qmlView = new QDeclarativeView();
m_qmlView->setSource(QUrl::fromLocalFile("source.qml")); //load qml file
m_qmlView->show();
return a.exec();
}
source.qml
import QtQuick 1.0
Rectangle {
id: page
width: 320; height: 240
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 }
//定义了名字为down的状态,属性是y==160, 旋转:180度;颜色:红色
states: State {
name: "down"; when: mouseArea.pressed == true
PropertyChanges {
target: helloText; y: 160; rotation:180; color:"red"
}
}
//从qml默认状态,到状态down的变换
transitions: Transition {
from: ""
to: "down"
reversible: true
ParallelAnimation{ //提供了并行的动画效果
NumberAnimation{properties: "y,rotation"; duration:500; easing.type: Easing.InOutQuad}
ColorAnimation {duration: 500 }
}
// SequentialAnimation{//顺序执行的动画效果
// 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 }
}
}
source.qml使用Cell自定义控件,Cell.qml
import QtQuick 1.0
Item {
id: container
property alias cellColor: rectangle.color
signal clicked(color cellColor)
width: 40; height: 25
Rectangle {
id: rectangle
border.color: "white"
anchors.fill: parent
}
MouseArea {
anchors.fill: parent
onClicked: container.clicked(container.cellColor)
}
}
库文件:Qt5Declaratived.lib Qt5Guid.lib Qt5Widgetsd.lib Qt5Cored.lib
环境: VS2010 + win7-64位 + Qt5.1.1
运行效果:点击 文本,实现动画效果运行效果: