QML入门教程(3)

185 篇文章 6 订阅
159 篇文章 2 订阅

经过前面两个教程,文字也能显示,也能处理鼠标事件了,来点动画吧。
Qml3.gif
这个教程实现了当鼠标按住的时候,Hello,World从顶部到底部的一个旋转过程,并带有颜色渐变的效果。

完整的源代码main.qml

import QtQuick 2.0
 
Rectangle {
id: page
width: 500; height: 200
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 { target: 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 }
}
}

除了这个main.qml之外,还有一个Cell.qml也是需要的,和教程(2)中的完全一样。下面来看一看比起教程(2)的代码增加出来的内容。

    Text{
...
states: State {
name: "down"; when: mouseArea.pressed == true
PropertyChanges { target: 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 }
}
}
...
}

states内嵌于Text之中,可以为Text元素添加多个状态,现在的这个例子只增加了一个状态。该状态的名为为”down”,然后由“when”指 定了什么时候触发这个状态。PropertyChanges则指定了哪个元素的哪些属性会发生什么样的变化。例子中PropertyChanges利用 “target”指定了id为”helloText”的元素会发生变化,包括其y,rotation,color等属性。
transitions 是用于增加动画效果的(如果把transitions这一段代码删去,Hello,World的文字也会发生变化,但是看不到中间动画渐变效果)。同样可 以看到transitions是复数形式,意味着可以添加多个动画过程。“from”和”to”指明了当前的动画作用于哪两个状态变化之间。 “from”和”to”的参数名来自于State中的”name”属性。
ParalleAnimation则指定了有多个 有多个动画并行发生。NumberAnimation用于qreal类型的属性变化,ColorAnimation则用于颜色变化。更多 Animation请在QML文档中查找”Animation and Transitions”。
好了,三篇教程到此结 束。

所有的源码可以在如下的地址下载:

bzr branch lp:~liu-xiao-guo/debiantrial/hello3

更多例程可以在Qt网站找到:https://qt-project.org/doc/qt-4.7/gettingstartedqml.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值