屬性動畫(PropertyAnimation)
PropertyAnimation是QML中最基礎、最常用的動畫類型,它可以對任何基于數字或顏色的屬性進行動畫化處理,實現平滑的過渡效果。
核心屬性與用法
PropertyAnimation的主要屬性如下表所示:
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
target | QtObject | 動畫作用的目標對象 | 父對象 |
property | string | 要動畫化的屬性名 | 必須指定 |
from | variant | 動畫起始值 | 當前屬性值 |
to | variant | 動畫結束值 | 必須指定 |
duration | int | 動畫持續時間(ms) | 250 |
easing.type | enumeration | 緩動曲線類型 | Easing.Linear |
easing.amplitude | real | 彈性動畫幅度 | 1.0 |
easing.period | real | 彈性動畫周期 | 0.3 |
loops | int | 循環次數 | 1 |
running | bool | 是否自動運行 | false |
alwaysRunToEnd | bool | 停止時是否完成動畫 | false |
基礎示例
import QtQuick 2.15Rectangle {id: rectwidth: 100; height: 100color: "red"x: 0// 基本屬性動畫PropertyAnimation {target: rectproperty: "x"to: 200duration: 1000running: true}
}
緩動曲線示例
PropertyAnimation支持多種緩動曲線,可以創建更自然的動畫效果:
PropertyAnimation {property: "rotation"to: 360easing.type: Easing.OutBounceeasing.amplitude: 2.0duration: 1000
}
相對值動畫
PropertyAnimation支持相對當前值的動畫:
PropertyAnimation {property: "x"to: myItem.x + 50 // 相對當前位置移動50像素duration: 500
}
多屬性動畫
可以同時對多個屬性應用動畫:
ParallelAnimation {PropertyAnimation { property: "x"; to: 100 }PropertyAnimation { property: "y"; to: 100 }PropertyAnimation { property: "opacity"; to: 0.5 }
}
PropertyAnimation的強大之處在于它的通用性,幾乎可以對任何QML元素的任何屬性進行動畫處理,是構建動態UI的基礎。
數字動畫(NumberAnimation)
NumberAnimation是PropertyAnimation的派生類,專門用于處理數值類型的屬性動畫,如位置、大小、旋轉角度等。
核心屬性
NumberAnimation繼承了PropertyAnimation的所有屬性,并特別優化了對數值類型的處理:
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
from | real | 動畫起始值 | 當前屬性值 |
to | real | 動畫結束值 | 必須指定 |
by | real | 相對變化量 | - |
其他屬性繼承自PropertyAnimation |
基本用法示例
import QtQuick 2.0Rectangle {width: 100; height: 100color: "red"// 數字動畫作為屬性值源NumberAnimation on x {to: 50duration: 1000}
}
三種寫法對比
NumberAnimation有三種主要使用方式:
?方法1:直接綁定屬性?
NumberAnimation on rotation {id: minutePinAnifrom: 0to: 360duration: 20000loops: Animation.Infinite
}
?方法2:獨立動畫對象?
NumberAnimation {id: minutePinAnitarget: minPinproperty: "rotation"to: 360duration: 10000loops: Animation.Infinite
}
?方法3:通過Behavior?
Behavior on rotation {NumberAnimation {from: 0to: 100duration: 20000loops: Animation.Infinite}
}
與RotationAnimation的區別
雖然NumberAnimation可以用于旋轉動畫,但QML提供了專門的RotationAnimation類型,它比NumberAnimation多了一個旋轉方向屬性:
RotationAnimation {target: itemproperty: "rotation"direction: RotationAnimation.Clockwise // 順時針方向from: 0to: 360duration: 1000
}
RotationAnimation的direction
屬性可以是:
RotationAnimation.Numerical
?(默認):數值線性插值RotationAnimation.Clockwise
:順時針旋轉RotationAnimation.Counterclockwise
:逆時針旋轉RotationAnimation.Shortest
:沿最短路徑旋轉
NumberAnimation因其簡單高效,在大多數數值動畫場景中都是首選方案,特別是當需要精確控制數值變化過程時。
預定義的目標和屬性動畫
QML提供了一種更簡潔的語法來定義屬性動畫,即直接在屬性上聲明動畫,這種方式稱為"預定義的目標和屬性動畫"或"on語法"。
基本語法
<AnimationType> on <property> {// 動畫屬性設置
}
典型示例
import QtQuick 2.0Rectangle {id: rectwidth: 100; height: 100color: "red"// 預定義x屬性的動畫PropertyAnimation on x {to: 100duration: 500}// 預定義y屬性的動畫PropertyAnimation on y {to: 100duration: 500}
}
特點與優勢
- ?簡潔性?:不需要指定target和property,代碼更簡潔
- ?自動綁定?:動畫自動綁定到聲明它的元素的對應屬性
- ?自動運行?:這種形式的動畫會在組件加載完成后自動開始運行
- ?適用于任何屬性?:可以對任何支持動畫的屬性使用此語法
實際應用案例
import QtQuick 2.15Rectangle {width: 200height: 200anchors.centerIn: parentcolor: "lightgreen"// 旋轉動畫RotationAnimation on rotation {from: 0to: 360duration: 2000loops: Animation.Infinite}// 縮放動畫ScaleAnimator on scale {from: 0.5to: 1.5duration: 1000loops: Animation.Infinite}// 透明度動畫OpacityAnimator on opacity {from: 0.3to: 1.0duration: 1500loops: Animation.Infinite}}
與獨立動畫的對比
相比于獨立的動畫聲明,預定義語法有以下區別:
特性 | 預定義語法 | 獨立動畫 |
---|---|---|
目標對象 | 隱含(父元素) | 需顯式指定 |
屬性綁定 | 自動關聯 | 需顯式指定 |
執行時機 | 自動開始 | 需手動啟動或設置running |
復用性 | 較低 | 較高 |
代碼量 | 較少 | 較多 |
預定義的目標和屬性動畫語法非常適合那些簡單、直接的動畫需求,特別是在原型設計或簡單動畫場景中,可以顯著減少代碼量并提高可讀性。
過渡動畫(Transition)
Transition用于定義狀態變化時的動畫效果,它可以在元素從一個狀態切換到另一個狀態時,自動應用指定的動畫。
核心屬性
Transition的主要屬性如下:
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
from | string | 起始狀態名 | "" (任何狀態) |
to | string | 目標狀態名 | "" (任何狀態) |
reversible | bool | 是否可反向播放 | false |
enabled | bool | 是否啟用過渡 | true |
animations | list | 動畫列表 | 空列表 |
基本用法
import QtQuick 2.15Rectangle {id: myRectwidth: 100; height: 100color: "red"state: "state1"MouseArea {anchors.fill: parentonPressed: myRect.state = "state2"onReleased: myRect.state = "state1"}states: [State {name: "state1"PropertyChanges { target: myRect; x: 0; y: 0 }},State {name: "state2"PropertyChanges { target: myRect; x: 100; y: 100 }}]transitions: [Transition {from: "state1"to: "state2"NumberAnimation { properties: "x,y"; duration: 500 }},Transition {from: "state2"to: "state1"NumberAnimation { properties: "x,y"; duration: 300 }}]}
?
多屬性過渡示例
transitions: Transition {// 顏色過渡ColorAnimation { duration: 1000 }// 位置過渡NumberAnimation { properties: "x,y"duration: 500 easing.type: Easing.OutBack}// 旋轉過渡RotationAnimation { duration: 700 direction: RotationAnimation.Clockwise}
}
高級用法:條件過渡
可以根據不同條件應用不同的過渡效果:
transitions: [Transition {from: "*"; to: "dragging"NumberAnimation { property: "scale"; to: 1.2; duration: 200 }},Transition {from: "dragging"; to: "*"SequentialAnimation {NumberAnimation { property: "scale"; to: 1.0; duration: 200 }SpringAnimation { property: "rotation"; spring: 2; damping: 0.2 }}}
]
與Behavior的區別
Transition和Behavior都用于屬性變化時的動畫,但有以下區別:
特性 | Transition | Behavior |
---|---|---|
觸發條件 | 狀態變化 | 任何屬性變化 |
作用范圍 | 狀態切換期間 | 始終有效 |
控制粒度 | 基于狀態 | 基于屬性 |
適用場景 | 明確的狀態機 | 持續性的屬性變化 |
Transition在創建有明確狀態劃分的界面時非常有用,如折疊/展開、激活/非激活等場景,能夠提供清晰的視覺反饋和狀態轉換指示。
默認行為動畫(Behavior)
Behavior是QML中用于對屬性值變化做隱式動畫的機制,它綁定到某個屬性上,當該屬性在運行時被修改時,會自動觸發預定義的動畫效果。
核心屬性
Behavior的主要屬性如下:
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
animation | Animation | 屬性變化時應用的動畫 | 必須指定 |
enabled | bool | 是否啟用行為動畫 | true |
基本語法
Behavior on <property> {<animation>
}
基礎示例
import QtQuick 2.15Rectangle {width: 100; height: 100color: "red"// 為x坐標變化添加行為動畫Behavior on x {NumberAnimation { duration: 500 }}MouseArea {anchors.fill: parentonClicked: parent.x = parent.x + 50}
}
常見內置Animation類型
Behavior可以與多種動畫類型配合使用:
類型 | 可動畫化屬性 | 說明 |
---|---|---|
NumberAnimation | 數值型(x, y, width...) | 通過線性或緩動曲線插值數值 |
ColorAnimation | color, border.color... | 在兩個顏色值之間漸變 |
RotationAnimation | rotation | 對旋轉角度做插值動畫 |
ScaleAnimation | scale | 對縮放因子做插值 |
SpringAnimation | 任意數值型 | 彈簧阻尼動畫,帶回彈效果 |
SmoothedAnimation | 任意數值型 | 平滑快速跟隨目標值 |
組合多個動畫
Behavior內部可以使用組合動畫實現復雜效果:
Behavior on width {SequentialAnimation {NumberAnimation { duration: 300; easing.type: Easing.OutQuad }PauseAnimation { duration: 100 }NumberAnimation { duration: 200; easing.type: Easing.InQuad }}
}
條件性行為
可以動態啟用或禁用Behavior:
Rectangle {id: rectproperty bool animationsEnabled: trueBehavior on x {enabled: rect.animationsEnabledNumberAnimation { duration: 200 }}
}
注意事項
- ?初始化賦值不會觸發?:組件創建時的初始設定不會觸發Behavior動畫
- ?性能考慮?:不要對大量快速變化的屬性綁定耗時動畫
- ?多重Behavior?:一個屬性只能有一個Behavior,但可以在內部使用ParallelAnimation/SequentialAnimation
- ?與visible屬性?:對visible屬性直接應用Behavior無效,可以改為對opacity應用動畫然后綁定visible到opacity > 0
Behavior的主要優勢在于它能夠降低動畫調用成本,無需在每次更改時手動啟動動畫,只需在組件聲明里一次性配置,后續所有對該屬性的改變都會平滑地過渡。
并行動畫與序列動畫(ParallelAnimation和SequentialAnimation)
QML提供了兩種組合動畫的方式:ParallelAnimation(并行動畫)和SequentialAnimation(序列動畫),它們作為容器可以嵌套其他動畫元素,實現復雜的動畫效果。
ParallelAnimation(并行動畫)
ParallelAnimation允許所有子動畫同時運行,適用于需要多個屬性同步動畫的場景。
核心屬性
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
animations | list | 子動畫列表 | 空列表 |
running | bool | 是否運行 | false |
loops | int | 循環次數 | 1 |
alwaysRunToEnd | bool | 停止時是否完成當前動畫 | false |
基本示例
import QtQuick 2.15Rectangle {id: rectwidth: 100; height: 100color: "red"x: 0; y: 0; opacity: 1.0ParallelAnimation {running: trueNumberAnimation { target: rect; property: "x"; to: 200; duration: 1000 }NumberAnimation { target: rect; property: "y"; to: 200; duration: 1500 }PropertyAnimation { target: rect; property: "opacity"; to: 0.5; duration: 800 }}
}
動態添加動畫
ParallelAnimation支持動態添加子動畫:
ParallelAnimation {id: dynamicAnim
}function addScaleAnimation() {var anim = Qt.createQmlObject('import QtQuick 2.15; NumberAnimation { property: "scale"; to: 2.0; duration: 500 }', dynamicAnim);dynamicAnim.addAnimation(anim);
}
SequentialAnimation(序列動畫)
SequentialAnimation按順序依次運行子動畫,適用于需要多個動畫按特定順序執行的場景。
核心屬性
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
animations | list | 子動畫列表 | 空列表 |
running | bool | 是否運行 | false |
loops | int | 循環次數 | 1 |
alwaysRunToEnd | bool | 停止時是否完成當前動畫 | false |
currentAnimation | Animation | 當前正在運行的子動畫 | null |
基本示例
import QtQuick 2.15Rectangle {id: rectwidth: 100; height: 100color: "red"x: 0; y: 0SequentialAnimation {running: trueNumberAnimation { target: rect; property: "y"; to: 200; duration: 1000 }ColorAnimation { target: rect; property: "color"; to: "blue"; duration: 500 }RotationAnimation { target: rect; property: "rotation"; to: 360; duration: 800 }}
}
組合動畫序列
可以嵌套ParallelAnimation和SequentialAnimation創建復雜動畫:
SequentialAnimation {// 第一階段:并行移動和旋轉ParallelAnimation {NumberAnimation { property: "x"; to: 200 }RotationAnimation { target: rotation; to: 90 }}// 第二階段:并行改變顏色和大小ParallelAnimation {ColorAnimation { property: "color"; to: "blue" }NumberAnimation { property: "width"; to: 150 }}// 第三階段:暫停后恢復PauseAnimation { duration: 500 }NumberAnimation { property: "scale"; to: 1.0; duration: 300 }
}
注意事項
- ?動畫控制?:子動畫的running屬性會被容器動畫控制,不應單獨設置
- ?持續時間?:ParallelAnimation的持續時間等于最長子動畫的持續時間
- ?性能考慮?:復雜的動畫組合可能需要更多的CPU資源
- ?調試技巧?:可以在動畫的running和completed信號中添加console.log跟蹤動畫狀態
ParallelAnimation和SequentialAnimation為QML動畫提供了強大的組合能力,通過它們的嵌套和組合,可以構建出幾乎任何復雜的動畫序列,滿足現代UI對動畫效果的各類需求。
動畫師動畫(Animator)
Animator是Qt Quick 2.2及以上版本引入的一種特殊動畫類型,與常規動畫不同,Animator直接在Qt Quick的場景圖渲染線程中執行,即使在UI線程繁忙時也能保持流暢的動畫效果。
核心優勢
- ?獨立于UI線程?:在UI線程阻塞時仍能流暢運行
- ?高性能?:直接在渲染線程執行,減少中間步驟
- ?專有類型?:針對特定屬性優化的動畫類型
- ?簡單易用?:語法與PropertyAnimation類似
Animator類型
QML提供了多種專門的Animator類型:
類型 | 作用屬性 | 描述 |
---|---|---|
XAnimator | x | 水平位置動畫 |
YAnimator | y | 垂直位置動畫 |
ScaleAnimator | scale | 縮放動畫 |
RotationAnimator | rotation | 旋轉動畫 |
OpacityAnimator | opacity | 透明度動畫 |
UniformAnimator | uniform | 著色器統一變量動畫 |
基本用法
import QtQuick Rectangle {id: rect1width: 100height: 100x: 10y: 10color: "red"XAnimator on x {from: 10to: 300duration: 2000loops: Animator.Infinite}YAnimator on y {from: 10to: 300duration: 2000loops: Animator.Infinite}ScaleAnimator on scale {from: 0.1to: 1.5duration: 2000loops: Animator.Infinite}OpacityAnimator on opacity {from: 0.1to: 1.0duration: 2000loops: Animator.Infinite}RotationAnimator on rotation {from: 0to: 360duration: 2000loops: Animator.Infinite}}
與PropertyAnimation的對比
特性 | Animator | PropertyAnimation |
---|---|---|
執行線程 | 渲染線程 | UI線程 |
UI阻塞時 | 繼續運行 | 可能卡頓 |
適用版本 | Qt Quick 2.2+ | 所有版本 |
性能 | 更高 | 一般 |
屬性支持 | 特定屬性 | 所有屬性 |
適用場景 | 高性能需求 | 通用需求 |
Animator類型特別適合那些需要高性能、流暢動畫的場景,特別是在UI線程可能有繁重任務時,使用Animator可以確保動畫不受影響,保持流暢運行。
精靈動畫(SpriteAnimations)--嵌入式使用較少,了解就好
精靈動畫是游戲開發和交互式應用中常見的技術,通過快速連續顯示一系列圖像幀來創建動畫效果。QML提供了SpriteSequence和Sprite元素來實現精靈動畫。
核心組件
- ?SpriteSequence?:精靈動畫的容器,管理多個Sprite動畫
- ?Sprite?:定義單個動畫序列
- ?AnimatedSprite?:簡化版的單動畫精靈(后面詳細介紹)
SpriteSequence屬性
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
currentSprite | string | 當前精靈動畫的名稱 | "" |
goalSprite | string | 目標精靈動畫 | "" |
interpolate | bool | 是否開啟插值運算 | true |
running | bool | 是否執行動畫 | true |
sprites | list | 精靈動畫集合 | 空列表 |
Sprite屬性
屬性 | 類型 | 描述 |
---|---|---|
name | string | 動畫名稱 |
source | url | 精靈圖片源 |
frameX | int | 起始幀的x坐標 |
frameY | int | 起始幀的y坐標 |
frameCount | int | 動畫幀數 |
frameWidth | int | 單幀寬度 |
frameHeight | int | 單幀高度 |
frameDuration | int | 每幀持續時間(ms) |
to | map | 過渡到其他動畫的名稱和權重 |
基本示例
import QtQuickWindow {width: 640height: 900visible: truetitle: qsTr("Hello World")MouseArea {anchors.fill: parentonClicked: {animation.start()}}SequentialAnimation {id: animation//腳本會在前一個動畫結束后、下一個動畫開始前執行//goalSprite屬性可以指定目標Sprite類型,指定該屬性后會無視過渡權重,而以最短的路徑到達目標動畫。即從still->blink->floating->flailing->falling這個順序播放動畫ScriptAction {script: image.goalSprite = "falling";}NumberAnimation {target: imageproperty: "y"to: 500duration: 12000}// 下降完成之后回到still動畫ScriptAction {script: {image.goalSprite = "";image.jumpTo("still")}}PropertyAction {target: imageproperty: "y"value: 0}}//精靈動畫的容器,管理多個Sprite動畫SpriteSequence {id: imagewidth: 256height: 256anchors.horizontalCenter: parent.horizontalCenterinterpolate: falsegoalSprite: "" //最終動畫// 權重的作用原理?// ?數值含義?:to對象中的鍵值對(如"still":1)表示從當前動畫切換到其他動畫的相對概率。// 例如,"still":1, "blink":0.1表示:// 切換到still動畫的概率是 1/(1+0.1) ≈ 90.9%// 切換到blink動畫的概率是 0.1/(1+0.1) ≈ 9.1%// ?權重為0?:如"floating":0表示禁止切換到該動畫// ?行為表現?:動畫播放時,系統會按權重比例隨機選擇下一狀態,still動畫有極高概率保持,偶爾觸發blink,而不會切換到floating// 靜止Sprite {name: "still"source: "BearSheet.png"frameCount: 1 //幀數frameWidth: 256 //幀的寬度和高度frameHeight: 256frameDuration: 100 //持續時間to: {"still": 1, //1代表權重"blink": 0.1,"floating": 0}}// 眨眼Sprite {name: "blink"source: "BearSheet.png"frameCount: 3frameX: 256frameY: 1536frameWidth: 256frameHeight: 256frameDuration: 100to: {"still": 1}}// 漂浮Sprite {name: "floating"source: "BearSheet.png"frameCount: 9frameX: 0frameY: 0frameWidth: 256frameHeight: 256frameDuration: 160to: {"still": 0,"flailing": 1}}// 擺動Sprite {name: "flailing"source: "BearSheet.png"frameCount: 8frameX: 0frameY: 768frameWidth: 256frameHeight: 256frameDuration: 160to: {"falling": 1}}// 下降Sprite {name: "falling"source: "BearSheet.png"frameCount: 5frameY: 1280frameWidth: 256frameHeight: 256frameDuration: 160to: {"falling": 1}}}
}
效果:
動畫過渡機制
SpriteSequence中的動畫可以通過to
屬性定義狀態轉換:
- ?隨機轉換?:根據權重隨機切換到其他動畫
- ?強制轉換?:通過設置
goalSprite
強制切換到指定動畫 - ?直接跳轉?:使用
jumpTo()
方法立即切換到指定動畫
使用場景
- 游戲角色動畫(行走、奔跑、跳躍等)
- 復雜的狀態轉換動畫
- 需要隨機或條件觸發動畫變化的場景
- 基于精靈圖的動畫效果
精靈動畫特別適合游戲開發和需要復雜動畫序列的應用,它能夠有效地組織和管理多個動畫狀態,并通過狀態轉換創建豐富的交互體驗。
動態精靈動畫(AnimatedSprite)--嵌入式使用較少,了解就好
AnimatedSprite是QML中用于實現幀動畫的簡化組件,適用于不需要復雜狀態管理的單一動畫序列。
核心屬性
AnimatedSprite的主要屬性如下:
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
frameCount | int | 動畫總幀數 | 1 |
frameRate | real | 每秒播放幀數 | - |
frameWidth | int | 單幀圖像寬度 | 元素寬度 |
frameHeight | int | 單幀圖像高度 | 元素高度 |
source | url | 精靈圖集路徑 | 必須指定 |
loops | int | 循環次數 | Animation.Infinite |
currentFrame | int | 當前幀索引 | 0 |
frameDuration | int | 每幀持續時間(ms) | - |
frameSync | bool | 是否同步顯示刷新率 | false |
interpolate | bool | 是否在幀間插值 | true |
paused | bool | 是否暫停 | false |
reverse | bool | 是否反向播放 | false |
running | bool | 是否運行 | true |
基本用法
import QtQuick 2.12
import QtQuick.Window 2.12Window {visible: truewidth: 800height: 600color: "black"title: "Qt基于Qml圖像幀動畫播放"AnimatedSprite {id: animatedwidth: 365height: 365anchors.centerIn: parentsource: "qrc:/numbers.png"frameWidth: 64frameHeight: 64frameDuration: 1000 // 每秒播放一幀frameCount: 10frameX: 0frameY: 0onCurrentFrameChanged: {info.text = "%1/%2".arg(animated.currentFrame).arg(animated.frameCount)}}// 控制界面Row {spacing: 20anchors.horizontalCenter: parent.horizontalCenteranchors.bottom: parent.bottomanchors.bottomMargin: 4Text {id: infowidth: 120height: 60color: "red"font.pixelSize: 38verticalAlignment: Text.AlignVCenterhorizontalAlignment: Text.AlignRight}Button {width: 120height: 60text: (animated.paused === true) ? "播放" : "暫停"onClicked: (animated.paused === true) ? animated.resume() : animated.pause()}Button {width: 120height: 60text: "單幀播放"onClicked: animated.advance()}Button {width: 120height: 60text: "重置"onClicked: animated.restart()}}
}
與SpriteSequence的對比
特性 | AnimatedSprite | SpriteSequence |
---|---|---|
復雜度 | 簡單 | 復雜 |
動畫數量 | 單一動畫 | 多動畫序列 |
狀態轉換 | 不支持 | 支持 |
性能 | 更高 | 略低 |
適用場景 | 簡單幀動畫 | 復雜動畫狀態機 |
?性能優化建議
- ?使用精靈圖集?:將多幀打包到一個圖像文件中,減少資源加載開銷
- ?合理設置幀率?:根據實際需要設置,避免不必要的渲染
- ?適時暫停?:當動畫不可見時暫停播放
- ?預加載資源?:提前加載動畫資源,避免運行時卡頓
- ?減少插值?:對于像素藝術風格動畫,關閉interpolate屬性
AnimatedSprite因其簡單易用和高效性能,成為實現簡單幀動畫的首選方案,特別適合游戲特效、加載動畫、簡單角色動畫等場景。
彈動效果(Flickable)
Flickable是Qt Quick中用于實現可拖動和彈動效果的元素,它提供了一個可以滾動的區域,用戶可以通過滑動手勢瀏覽超出顯示區域的內容。
核心屬性
Flickable的主要屬性如下:
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
contentWidth | real | 內容寬度 | 必須指定 |
contentHeight | real | 內容高度 | 必須指定 |
contentX | real | 當前水平位置 | 0 |
contentY | real | 當前垂直位置 | 0 |
flickableDirection | enum | 滑動方向(Flickable.AutoFlickDirection等) | AutoFlickDirection |
boundsBehavior | enum | 邊界行為(Flickable.StopAtBounds等) | StopAtBounds |
maximumFlickVelocity | real | 最大滑動速度(像素/秒) | 平臺相關 |
flickDeceleration | real | 滑動減速度 | 平臺相關 |
interactive | bool | 是否允許用戶交互 | true |
pixelAligned | bool | 是否像素對齊 | false |
pressDelay | int | 按下延遲時間(ms) | 0 |
基本用法
import QtQuick 2.5
import QtQuick.Window 2.2Window {visible: truewidth: 640height: 480title: qsTr("Flickable Demo")Flickable {id: flickableinteractive: trueanchors.fill: parentcontentWidth: 1000contentHeight: 1000boundsBehavior: Flickable.StopAtBounds// 內容項 - 一個大圖像Image {id: imagesource: "kun.jpg"width: 1000height: 1000}}// 添加滾動條指示ScrollBar {id: vbarwidth: 12height: flickable.heightanchors.right: flickable.rightorientation: Qt.Verticalposition: flickable.visibleArea.yPositionsize : flickable.visibleArea.heightRatioonPositionChanged: {if (active) flickable.contentY = position * (flickable.contentHeight );}}ScrollBar {id: hbarwidth: flickable.widthheight: 12anchors.bottom: flickable.bottomorientation: Qt.Horizontalposition: flickable.visibleArea.xPositionsize : flickable.visibleArea.widthRatioonPositionChanged: {if (active) flickable.contentX = position * (flickable.contentWidth );}}
}
動態內容示例
Flickable常用于顯示動態生成的內容:
Flickable {anchors.fill: parentcontentWidth: col.widthcontentHeight: col.heightColumn {id: colwidth: parent.widthRepeater {model: 50delegate: Rectangle {width: col.widthheight: 60color: index % 2 ? "lightgray" : "white"Text {text: "Item " + indexfont.pixelSize: 20anchors.centerIn: parent}}}}
}
高級用法:自定義回彈效果
Flickable的rebound
屬性允許開發者自定義內容回彈到邊界時的過渡動畫效果:
Flickable {width: 200; height: 200contentWidth: 400; contentHeight: 400boundsBehavior: Flickable.DragOverBoundsrebound: Transition {NumberAnimation {properties: "x,y"duration: 1000easing.type: Easing.OutBounce}}Rectangle {width: 400; height: 400gradient: Gradient {GradientStop { position: 0.0; color: "lightsteelblue" }GradientStop { position: 1.0; color: "blue" }}}
}
邊界行為詳解
Flickable提供了多種邊界行為控制方式:
- ?StopAtBounds?(默認):內容不能拖動到邊界之外,輕拂也不會超調
- ?DragOverBounds?:內容可以拖動到邊界之外,但輕拂不會超調
- ?OvershootBounds?:輕拂時可以超過邊界,但不能拖動到邊界之外
- ?DragAndOvershootBounds?:內容可以拖動到邊界之外,輕拂時也可以超過邊界
性能優化技巧
- ?設置clip屬性?:對于非全屏Flickable,應將
clip
設為true以避免渲染開銷 - ?合理使用pixelAligned?:對于像素精確的內容,啟用
pixelAligned
可避免亞像素渲染 - ?動態加載內容?:對于超長列表,考慮使用動態加載技術
- ?避免過度繪制?:優化內容項的繪制邏輯
翻轉效果(Flipable)
Flipable是QML中用于實現3D翻轉效果的元素,可以創建卡片翻轉、面板切換等視覺效果。
核心屬性
屬性 | 類型 | 描述 | 默認值 |
---|---|---|---|
front | Item | 正面顯示的項 | 必須指定 |
back | Item | 背面顯示的項 | 可選 |
side | enumeration | 當前顯示的面(Front或Back) | Front |
transform | list | 應用的變換列表 | 空列表 |
axis | vector3d | 旋轉軸(x,y,z) | (0,1,0) |
angle | real | 當前旋轉角度(度) | 0 |
基本用法
import QtQuickWindow {width: 640height: 480visible: truetitle: qsTr("Hello World")Flipable {id: flipablewidth: 240height: 240anchors.centerIn: parentproperty bool flipped: falsedfront: Image {source: "front.png"anchors.centerIn: parent}back: Image {source: "back.png"anchors.centerIn: parent}transform: Rotation {id: rotationorigin.x: flipable.width / 2origin.y: flipable.height / 2axis.x: 0axis.y: 1axis.z: 0angle: 0}states: State {name: "back"when: flipable.flippedPropertyChanges {target: rotationangle: 180}}transitions: Transition {NumberAnimation {target: rotationproperty: "angle"duration: 500}}MouseArea {anchors.fill: parentonClicked: {flipable.flipped = !flipable.flipped}}}
}
?
性能優化建議
- ?簡化內容?:Flipable的兩面內容應盡量簡單,避免復雜嵌套
- ?合理使用Perspective?:在父元素上設置
Perspective
變換可增強3D效果 - ?避免頻繁切換?:翻轉動畫較耗資源,不宜頻繁觸發
- ?預渲染內容?:對于復雜內容,考慮使用
ShaderEffect
預渲染
總結
QML提供了豐富而強大的動畫系統,從基礎的屬性動畫到復雜的3D效果,開發者可以創建各種流暢的交互體驗。關鍵要點包括:
- ?選擇合適的動畫類型?:根據場景選擇PropertyAnimation、Behavior或Animator
- ?組合使用動畫?:利用ParallelAnimation和SequentialAnimation創建復雜序列
- ?性能優化?:對于頻繁觸發的動畫,優先考慮Animator類型
- ?狀態管理?:合理使用State和Transition管理界面狀態變化