新手必學(xué) QML入門教程 (3)
QML是Qt推出的Qt Quick技術(shù)的一部分,是一種新增的簡(jiǎn)便易學(xué)的語(yǔ)言。QML是一種陳述性語(yǔ)言,用來(lái)描述一個(gè)程序的用戶界面:無(wú)論是什么樣子,以及它如何表現(xiàn)。
經(jīng)過(guò)前面兩個(gè)教程,文字也能顯示,也能處理鼠標(biāo)事件了,來(lái)點(diǎn)動(dòng)畫吧。
這個(gè)教程實(shí)現(xiàn)了當(dāng)鼠標(biāo)按住的時(shí)候,Hello,World從頂部到底部的一個(gè)旋轉(zhuǎn)過(guò)程,并帶有顏色漸變的效果。
完整的源代碼main.qml
- import Qt 4.7
- 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 }
- }
- }
除了這個(gè)main.qml之外,還有一個(gè)Cell.qml也是需要的,和教程(2)中的完全一樣。下面來(lái)看一看比起教程(2)的代碼增加出來(lái)的內(nèi)容。
- 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內(nèi)嵌于Text之中,可以為Text元素添加多個(gè)狀態(tài),現(xiàn)在的這個(gè)例子只增加了一個(gè)狀態(tài)。該狀態(tài)的名為為”down”,然后由“when”指 定了什么時(shí)候觸發(fā)這個(gè)狀態(tài)。PropertyChanges則指定了哪個(gè)元素的哪些屬性會(huì)發(fā)生什么樣的變化。例子中PropertyChanges利用 “target”指定了id為”helloText”的元素會(huì)發(fā)生變化,包括其y,rotation,color等屬性。
transitions 是用于增加動(dòng)畫效果的(如果把transitions這一段代碼刪去,Hello,World的文字也會(huì)發(fā)生變化,但是看不到中間動(dòng)畫漸變效果)。同樣可以看到transitions是復(fù)數(shù)形式,意味著可以添加多個(gè)動(dòng)畫過(guò)程。“from”和”to”指明了當(dāng)前的動(dòng)畫作用于哪兩個(gè)狀態(tài)變化之間。 “from”和”to”的參數(shù)名來(lái)自于State中的”name”屬性。
ParalleAnimation則指定了有多個(gè) 有多個(gè)動(dòng)畫并行發(fā)生。NumberAnimation用于qreal類型的屬性變化,ColorAnimation則用于顏色變化。更多 Animation請(qǐng)?jiān)?strong>QML文檔中查找”Animation and Transitions”。
小結(jié):三篇關(guān)于QML教程到此結(jié)束。不管是文字顯示,還是簡(jiǎn)單的動(dòng)畫效果,相信你可以和諧的去完成,希望本篇文章對(duì)你有所幫助。