文章目錄
- 一、概述
- 二、常用基本元素
- 2.1 基礎視覺元素(常用于布局和顯示)
- 2.1.1 元素 Item 的介紹和使用
- 2.1.2 元素 Rectangle 的介紹和使用
- 2.1.3 元素 Image 的介紹和使用
- 2.1.4 元素 Text 的介紹和使用
- 2.2 交互元素(用于接收用戶操作)
- 2.2.1 元素 MouseArea 介紹和使用
- 2.2.2 元素 FocusScope 的介紹和使用
- 2.2.3 元素 Keys 介紹和使用
- 2.3 布局元素(用于排版、排列)
- 2.3.1 元素 Row 的介紹和使用
- 2.3.2 元素 Column 的介紹和使用
- 2.3.3 元素 Grid 的介紹和使用
- 2.3.4 元素 Flow 的介紹和使用
- 2.3.5 元素 StackLayout 的介紹和使用
- 2.3.6 元素 StackView 的介紹和使用
- 2.4 動畫與狀態元素(實現過渡、動畫、動態切換)
- 2.4.1 元素 States 的介紹和使用
- 2.4.2 元素 Transitions 的介紹和使用
- 2.4.3 PropertyAnimation(屬性動畫)
- 2.4.4 NumberAnimation(數值動畫)
- 2.4.5 ColorAnimation(顏色動畫)
- 2.4.6 SequentialAnimation(順序動畫)
- 2.4.7 ParallelAnimation(并行動畫)
一、概述
??在 QML 中,基本元素(Basic Elements) 是構建 UI 界面的核心組件。QML 采用聲明式語法,通過這些元素定義界面結構、行為和交互。元素可以被分為可視化元素與非可視化元素。一個可視化元素(例如矩形框Rectangle)有著幾何形狀并且可以在屏幕上顯示。一個非可視化元素(例如計時器Timer)提供了常用的功能,通常用于操作可視化元素。
二、常用基本元素
2.1 基礎視覺元素(常用于布局和顯示)
2.1.1 元素 Item 的介紹和使用
??在 QML 中,Item 是最基礎的可視元素之一,許多其他圖形元素(如 Rectangle、Image、Text 等)都直接或間接繼承自 Item。它本身不繪制任何內容,但可以用于組織、布局和管理子項。
基本介紹:
Item {id: rootItemwidth: 200height: 100
}
- Item 代表一個矩形區域,它本身不可見。
- 可以包含子元素,是容器型組件。
- 具有基本的坐標屬性(x, y, width, height,anchors 等)。
- 常用于組合多個組件或布局結構中。
常用屬性:
常見用途:
用作容器,組織子元素
Item {width: 300; height: 100Rectangle {width: 100; height: 100; color: "red"}Rectangle {x: 120width: 100; height: 100; color: "blue"}
}
用于布局錨定
Item {width: 200; height: 200Rectangle {width: 50; height: 50; color: "green"anchors.centerIn: parent}
}
示例演示:
import QtQuick 2.15
import QtQuick.Window 2.15Window {width: 400height: 300visible: truetitle: qsTr("Item 示例")// Item 是一個無可視外觀的容器Item {id: containerwidth: 300height: 200anchors.centerIn: parent// 第一個子元素Rectangle {width: 100height: 100color: "lightblue"x: 0y: 0}// 第二個子元素Rectangle {width: 100height: 100color: "lightgreen"x: 120y: 50}}
}
效果如下:
2.1.2 元素 Rectangle 的介紹和使用
??Rectangle 是 QML 中最常用的可視化元素之一,用于繪制一個矩形區域。它可以設置顏色、大小、圓角、邊框、漸變、陰影等屬性,常用于 UI 中的背景、按鈕、面板等組件。
基本語法:
Rectangle {width: 200height: 100color: "lightblue"
}
常用屬性說明:
示例 1:簡單矩形
Rectangle {width: 150height: 80color: "orange"
}
示例 2:帶邊框和圓角
Rectangle {width: 200height: 100color: "white"radius: 10border.color: "black"border.width: 2
}
示例 3:漸變背景
Rectangle {width: 200height: 100gradient: Gradient {GradientStop { position: 0.0; color: "red" }GradientStop { position: 1.0; color: "yellow" }}
}
示例 4:響應點擊
Rectangle {width: 100height: 100color: "lightgray"MouseArea {anchors.fill: parentonClicked: {parent.color = "green"}}
}
2.1.3 元素 Image 的介紹和使用
??Image 是 QML 中用于顯示圖像的元素。它繼承自 Item,可以加載本地圖片或網絡圖片,支持縮放、填充模式、異步加載、緩存等功能。
基本語法:
Image {source: "my_picture.png"width: 100height: 100
}
常用屬性:
fillMode 填充模式:
示例 1:加載本地圖片
Image {source: "qrc:/images/logo.png"width: 100height: 100fillMode: Image.PreserveAspectFit
}
示例 2:加載網絡圖片
Image {source: "https://example.com/image.jpg"asynchronous: truecache: truewidth: 200height: 150
}
示例 4:點擊更換圖片
Image {id: dynamicImagesource: "img1.png"width: 100height: 100MouseArea {anchors.fill: parentonClicked: {dynamicImage.source = "img2.png"}}
}
2.1.4 元素 Text 的介紹和使用
在 QML 中,Text 元素用于顯示一段文本,是最基本的文字展示組件,具有強大的排版和樣式能力。
基本語法:
Text {text: "Hello, QML!"font.pixelSize: 20color: "black"
}
常用屬性:
wrapMode 換行模式:
示例一:顯示帶樣式的文本
Text {text: "歡迎使用 QML!"color: "#1684DF"font.pixelSize: 24font.bold: trueanchors.centerIn: parent
}
示例二:多行文本 + 自動換行
Text {text: "這是一段很長的文本,用于測試自動換行是否有效。"width: 200wrapMode: Text.Wrap
}
示例三:超出省略顯示(elide)
Text {text: "這是一個超出顯示寬度的文本"width: 150elide: Text.ElideRight
}
示例四:HTML 文本支持
Text {text: "<b>加粗</b> <i>斜體</i> <font color='red'>紅色</font>"textFormat: Text.RichText
}
示例五:點擊文本實現交互
Text {id: clickableTexttext: "點擊我"color: "blue"MouseArea {anchors.fill: parentonClicked: {clickableText.text = "你點擊了我!"}}
}
2.2 交互元素(用于接收用戶操作)
2.2.1 元素 MouseArea 介紹和使用
在 QML 中,MouseArea 是一個 用于處理鼠標交互的基礎元素,常用于響應點擊、按下、釋放、移動等事件。
基本語法:
MouseArea {anchors.fill: parent // 鼠標區域覆蓋整個父項onClicked: {console.log("鼠標被點擊了")}
}
常用屬性說明:
常用信號(事件):
示例:點擊改變顏色
Rectangle {width: 200; height: 200color: "lightblue"MouseArea {anchors.fill: parentonClicked: {parent.color = "lightgreen"console.log("點擊了矩形")}}
}
示例:懸停改變鼠標樣式
Rectangle {width: 100; height: 100; color: "lightgray"MouseArea {anchors.fill: parenthoverEnabled: truecursorShape: Qt.PointingHandCursoronEntered: console.log("鼠標進入區域")onExited: console.log("鼠標離開區域")}
}
示例:獲取鼠標位置
MouseArea {anchors.fill: parentonPositionChanged: {console.log("鼠標位置:", mouse.x, mouse.y)}
}
2.2.2 元素 FocusScope 的介紹和使用
??在 QML 中,FocusScope 是一個 專門用于組織焦點(Focus)管理的容器元素。當你在組件中有多個可以獲取焦點的子項時,使用 FocusScope 可以更清晰地控制哪個子控件獲取焦點,避免焦點混亂。FocusScope 繼承自 Item,本身不會獲得焦點,但它能確保它內部的某個元素獲得焦點時,焦點不會被傳遞到 FocusScope 外部。
基本語法:
FocusScope {Rectangle {width: 200; height: 40; color: "lightblue"TextInput {id: input1anchors.centerIn: parentfocus: true // 初始獲得焦點}}
}
示例1:多個輸入框
FocusScope {width: 300; height: 100Column {spacing: 10TextInput {id: input1width: 200; height: 30placeholderText: "輸入框 1"focus: true}TextInput {id: input2width: 200; height: 30`在這里插入代碼片`placeholderText: "輸入框 2"}}
}
說明:這個 FocusScope 確保焦點不會傳遞到它之外,而是在 input1 和 input2 內部管理。
示例2:在組件中封裝 FocusScope
// MyInputField.qml
FocusScope {width: 200; height: 40Rectangle {anchors.fill: parentcolor: "white"; border.color: "gray"TextInput {id: inputanchors.fill: parentanchors.margins: 4focus: true}}
}
// main.qml
Column {spacing: 20MyInputField {}MyInputField {}
}
說明:即使你復用了 MyInputField,FocusScope 也能確保每個組件內部焦點獨立。
注意事項:
- 不能僅靠 focus: true 管理多個控件焦點,需要用 FocusScope 做容器。
- 使用 Keys.onPressed 等鍵盤事件時,焦點必須在某個 focus: true 的控件上。
- 一個組件內部只能有一個主動獲取焦點的控件,多個控件都設置 focus: true 會導致焦點沖突。
2.2.3 元素 Keys 介紹和使用
??在 QML 中,Keys 是一個 用于處理鍵盤事件的附加屬性對象,可以附加到可獲得焦點的元素(如 Item、TextInput、TextField 等)上,以響應鍵盤輸入。
基本用途:
Item {focus: true // 只有獲得焦點的元素才能接收鍵盤事件Keys.onPressed: {if (event.key === Qt.Key_Enter || event.key === Qt.Key_Return) {console.log("回車鍵被按下")event.accepted = true // 表示已處理該事件,阻止繼續傳播}}
}
常用信號:
常見按鍵常量(來自 Qt.Key_*):
示例:方向鍵控制方塊移動
Rectangle {width: 300; height: 300; color: "white"Rectangle {id: boxwidth: 50; height: 50; color: "blue"x: 0; y: 0focus: trueKeys.onPressed: {const step = 10;if (event.key === Qt.Key_Right) {box.x += step;} else if (event.key === Qt.Key_Left) {box.x -= step;} else if (event.key === Qt.Key_Up) {box.y -= step;} else if (event.key === Qt.Key_Down) {box.y += step;}}}
}
注意事項:
- 必須設置 focus: true 才能接收鍵盤事件
- 如果鍵盤事件被多個元素監聽,優先處理具有焦點的元素
- event.accepted = true 表示事件已處理,防止冒泡
示例:Tab 鍵切換焦點
TextField {id: input1focus: trueKeys.onPressed: {if (event.key === Qt.Key_Tab) {input2.forceActiveFocus()event.accepted = true}}
}TextField {id: input2
}
示例:監聽組合鍵(如 Ctrl + S)
Keys.onPressed: {if (event.key === Qt.Key_S && event.modifiers & Qt.ControlModifier) {console.log("Ctrl+S 被按下")event.accepted = true}
}
2.3 布局元素(用于排版、排列)
2.3.1 元素 Row 的介紹和使用
在 QML 中,Row 是一個非常常用的 可視化布局元素,用于將子元素按水平方向依次排列。
基本語法:
Row {spacing: 10 // 子元素之間的間距Rectangle { width: 50; height: 50; color: "red" }Rectangle { width: 50; height: 50; color: "green" }Rectangle { width: 50; height: 50; color: "blue" }
}
常用屬性:
示例1:簡單的水平排列
Row {anchors.centerIn: parentspacing: 20Rectangle { width: 80; height: 40; color: "lightblue" }Rectangle { width: 80; height: 40; color: "lightgreen" }Rectangle { width: 80; height: 40; color: "lightpink" }
}
示例2:嵌套使用(Row + Column)
Column {spacing: 10Text { text: "用戶名:" }Row {spacing: 5Text { text: "賬號:" }TextField { width: 150 }}Row {spacing: 5Text { text: "密碼:" }TextField { width: 150; echoMode: TextInput.Password }}
}
示例3:設置排列方向為從右到左
Row {layoutDirection: Qt.RightToLeftspacing: 10Rectangle { width: 60; height: 40; color: "orange" }Rectangle { width: 60; height: 40; color: "yellow" }Rectangle { width: 60; height: 40; color: "gray" }
}
特性說明:
- Row 是 自動計算自身大小 的容器,默認高度為最高子項的高度,寬度為所有子項寬度之和加 spacing。
- Row 不會自動換行。如果你需要換行布局,可以使用 Flow。
- 子項可以通過 Layout.alignment 等屬性進一步對齊(但前提是搭配 RowLayout 使用,而非 Row)。
2.3.2 元素 Column 的介紹和使用
??在 QML 中,Column 是一個 基礎的布局容器元素,它會自動將子元素 按垂直方向(從上到下)依次排列,適合用于表單、列表、按鈕組等豎向布局場景。
基本語法:
Column {spacing: 10 // 子元素之間的間距Rectangle { width: 100; height: 40; color: "lightblue" }Rectangle { width: 100; height: 40; color: "lightgreen" }Rectangle { width: 100; height: 40; color: "lightpink" }
}
常用屬性:
示例:簡單的垂直排列
Column {anchors.centerIn: parentspacing: 12Button { text: "開始" }Button { text: "暫停" }Button { text: "退出" }
}
示例:表單布局(使用 Column 嵌 Row)
Column {spacing: 10anchors.centerIn: parentRow {spacing: 10Text { text: "用戶名:" }TextField { width: 150 }}Row {spacing: 10Text { text: "密碼:" }TextField { width: 150; echoMode: TextInput.Password }}Button {text: "登錄"anchors.horizontalCenter: parent.horizontalCenter}
}
Column 的局限性:
- 不會自動適配父容器寬度:默認只包裹內容大小
- 無法設置子項的對齊方式:所有子項默認左對齊,不能設置右對齊或居中(需手動處理)
- 不支持 Layout.* 屬性:想用自動填充、拉伸等特性時,應該用 ColumnLayout
2.3.3 元素 Grid 的介紹和使用
??在 QML 中,Grid 是一個用于 網格布局 的容器,它會將子元素按照指定的 行列數量 自動排列,類似于 HTML 的表格或 Excel 表格的布局效果。
基本語法:
Grid {rows: 2columns: 3spacing: 10 // 子項之間的間距Rectangle { width: 60; height: 40; color: "red" }Rectangle { width: 60; height: 40; color: "green" }Rectangle { width: 60; height: 40; color: "blue" }Rectangle { width: 60; height: 40; color: "orange" }Rectangle { width: 60; height: 40; color: "yellow" }Rectangle { width: 60; height: 40; color: "purple" }
}
上面例子中,Grid 設定了 2 行 3 列。子項會從左到右,從上到下依次填入。
最終布局如下(顏色代表每個矩形):
| red | green | blue |
| orange | yellow | purple |
常用屬性:
注意:rows 和 columns 至少設置一個,否則 Grid 無法正常布局。
示例:固定列數,自適應行數
Grid {columns: 3columnSpacing: 8rowSpacing: 8Repeater {model: 10Rectangle {width: 50; height: 50color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1.0)}}
}
示例:制作按鈕九宮格
Grid {columns: 3spacing: 6Repeater {model: 9Button {text: (index + 1).toString()width: 80height: 50}}
}
示例:Grid + Text + Image 布局(聯系人)
Grid {columns: 2spacing: 10Repeater {model: 4Rectangle {width: 150; height: 60; color: "#e0e0e0"Row {anchors.fill: parentanchors.margins: 8spacing: 10Image {source: "avatar.png"width: 40; height: 40fillMode: Image.PreserveAspectFit}Column {Text { text: "姓名:張三" }Text { text: "電話:123456789" }}}}}
}
2.3.4 元素 Flow 的介紹和使用
??在 QML 中,Flow 是一個布局容器,它會將子元素從 左到右水平排列,當一行排滿時,自動換行到下一行。適用于 標簽云、圖片展示、動態按鈕列表等內容數量不定、寬度可能變化的場景。
基本用法:
Flow {width: 300spacing: 10Rectangle { width: 80; height: 40; color: "lightblue" }Rectangle { width: 100; height: 40; color: "lightgreen" }Rectangle { width: 120; height: 40; color: "lightpink" }Rectangle { width: 60; height: 40; color: "orange" }Rectangle { width: 90; height: 40; color: "yellow" }
}
效果說明:
- 子項先在當前行從左到右排布
- 若子項寬度之和超過 Flow 寬度,會自動換到下一行
- 支持動態子項數量和大小,非常適合適配寬度變化
常用屬性:
示例:標簽自動換行展示
Flow {width: 300spacing: 8Repeater {model: ["C++", "Python", "JavaScript", "Rust", "Go", "Qt", "QML", "OpenCV"]Rectangle {height: 30width: textItem.width + 20color: "#d0e8ff"radius: 4Text {id: textItemanchors.centerIn: parenttext: modelDatafont.pixelSize: 14}}}
}
示例:方向從上往下排列(flow: TopToBottom)
Flow {width: 300height: 300spacing: 5flow: Flow.TopToBottomRepeater {model: 10Rectangle {width: 80; height: 40color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1)}}
}
示例:按鈕列表(自動換行)
Flow {width: 320spacing: 10Repeater {model: 15Button {text: "按鈕" + index}}
}
特點總結:
2.3.5 元素 StackLayout 的介紹和使用
??在 QML 中,StackLayout 是一個用于 堆疊多個子項并一次只顯示一個 的布局容器。它非常適合做 頁面切換、多步表單、標簽頁內容切換 等場景。
基本概念:
- StackLayout 將子項疊放在一起(Z 方向),只顯示當前索引對應的一個子項。
- 通過修改其 currentIndex 屬性來切換顯示的子項。
最簡用法示例:
import QtQuick 2.12
import QtQuick.Controls 2.12ApplicationWindow {visible: truewidth: 400height: 300title: "StackLayout 示例"Column {spacing: 10anchors.centerIn: parent// 頁面切換按鈕Row {spacing: 10Button { text: "頁面 1"; onClicked: stack.currentIndex = 0 }Button { text: "頁面 2"; onClicked: stack.currentIndex = 1 }Button { text: "頁面 3"; onClicked: stack.currentIndex = 2 }}// StackLayout 布局:只顯示當前索引的項StackLayout {id: stackwidth: 300height: 200Rectangle {color: "lightblue"anchors.fill: parentText { text: "第一頁"; anchors.centerIn: parent }}Rectangle {color: "lightgreen"anchors.fill: parentText { text: "第二頁"; anchors.centerIn: parent }}Rectangle {color: "lightpink"anchors.fill: parentText { text: "第三頁"; anchors.centerIn: parent }}}}
}
結合 Repeater + StackLayout 實現動態內容:
property int pageCount: 5StackLayout {id: stackcurrentIndex: 0width: 300; height: 200Repeater {model: pageCountRectangle {color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1)anchors.fill: parentText {anchors.centerIn: parenttext: "頁面 " + (index + 1)font.pixelSize: 20}}}
}
常用屬性和信號:
2.3.6 元素 StackView 的介紹和使用
??在 QML 中,StackView 是一個強大的頁面管理組件,它維護一個頁面堆棧,支持頁面的 push(進入)、pop(返回) 和 replace(替換) 操作,且帶有默認的頁面切換動畫。
非常適合用來實現:
- 多頁面導航(如設置頁、詳情頁)
- 向前/向后導航操作
- 嵌套導航結構
基本結構示例:
import QtQuick 2.12
import QtQuick.Controls 2.12ApplicationWindow {visible: truewidth: 400height: 300title: "StackView 示例"StackView {id: stackViewanchors.fill: parentinitialItem: Page1 {}}
}
示例頁面 Page1.qml
import QtQuick 2.12
import QtQuick.Controls 2.12Item {width: 400; height: 300Column {anchors.centerIn: parentspacing: 10Text { text: "這是第一頁" }Button {text: "跳轉到第二頁"onClicked: stackView.push(Qt.resolvedUrl("Page2.qml"))}}
}
示例頁面 Page2.qml
import QtQuick 2.12
import QtQuick.Controls 2.12Item {width: 400; height: 300Column {anchors.centerIn: parentspacing: 10Text { text: "這是第二頁" }Button {text: "返回上一頁"onClicked: stackView.pop()}}
}
常用操作:
屬性與信號:
與 StackLayout 對比:
2.4 動畫與狀態元素(實現過渡、動畫、動態切換)
2.4.1 元素 States 的介紹和使用
??在 QML 中,States 是用來定義 同一個組件在不同狀態下的屬性變化 的一種機制。它讓你可以很方便地為 UI 元素設置多個狀態(如“默認”、“選中”、“禁用”等),并在狀態之間切換時自動應用屬性變化。
基本語法結構:
Item {id: myItemwidth: 200height: 200color: "lightblue"states: [State {name: "redState"PropertyChanges {target: myItemcolor: "red"}},State {name: "greenState"PropertyChanges {target: myItemcolor: "green"}}]// 事件或條件觸發狀態改變MouseArea {anchors.fill: parentonClicked: {if (myItem.state === "redState")myItem.state = "greenState"elsemyItem.state = "redState"}}
}
關鍵概念解釋:
- states:一個包含多個 State 的數組。
- State.name:狀態的名字,用于切換時識別。
- PropertyChanges:在這個狀態下,哪些屬性會發生變化。
- target:要修改的對象。
- state屬性:用于設置或讀取當前狀態。
補充:Transitions(狀態切換動畫)
可以用 transitions 來定義從一個狀態切換到另一個狀態時的動畫:
transitions: Transition {NumberAnimation { properties: "color"; duration: 300 }
}
示例:按鈕點擊改變大小
Rectangle {id: boxwidth: 100height: 100color: "steelblue"states: State {name: "expanded"PropertyChanges {target: boxwidth: 200height: 200}}MouseArea {anchors.fill: parentonClicked: box.state = (box.state === "expanded" ? "" : "expanded")}transitions: Transition {NumberAnimation { properties: "width,height"; duration: 300 }}
}
注意:
- 動畫效果只能作用于屬性的變化,不能作用于結構(如刪除或添加組件)
- 如果想要動畫始終生效,可以使用 Behavior 元素,它不依賴于 States。
2.4.2 元素 Transitions 的介紹和使用
??在 QML 中,Transitions 是配合 States 使用的,用來定義在狀態變化時屬性變化的動畫效果。通過 Transition,你可以讓屬性的改變看起來更自然、平滑,比如淡入淡出、大小變換、顏色漸變等。
基本語法結構:
Item {id: boxwidth: 100height: 100color: "lightblue"states: State {name: "big"PropertyChanges {target: boxwidth: 200height: 200color: "steelblue"}}transitions: Transition {from: "*"to: "big"reversible: trueNumberAnimation { properties: "width,height"; duration: 300 }ColorAnimation { properties: "color"; duration: 300 }}MouseArea {anchors.fill: parentonClicked: box.state = (box.state === "big" ? "" : "big")}
}
關鍵屬性解釋:
- from:動畫的起始狀態名稱,可以是 “*” 表示任意狀態。
- to:動畫的目標狀態名稱。
- reversible:是否允許動畫反轉播放(默認 false)。
- properties:哪些屬性應用該動畫(如 “width,height”)。
多種動畫類型支持:
示例:點擊改變透明度和大小,使用動畫
Rectangle {id: rectwidth: 100; height: 100color: "tomato"opacity: 1.0states: State {name: "fade"PropertyChanges {target: rectopacity: 0.3width: 150height: 150}}transitions: Transition {from: "*"to: "fade"reversible: trueParallelAnimation {NumberAnimation { properties: "opacity,width,height"; duration: 500 }}}MouseArea {anchors.fill: parentonClicked: rect.state = (rect.state === "fade" ? "" : "fade")}
}
完整的交互演示示例:
import QtQuick 2.12
import QtQuick.Controls 2.12ApplicationWindow {visible: truewidth: 400height: 300title: "States & Transitions 示例"Rectangle {id: rootanchors.fill: parentcolor: "#f0f0f0"Rectangle {id: boxwidth: 100height: 100color: "blue"opacity: 1.0anchors.centerIn: parentradius: 10// 定義狀態states: [State {name: "normal"PropertyChanges { target: box; opacity: 1.0; width: 100; height: 100 }},State {name: "fade"PropertyChanges { target: box; opacity: 0.2; width: 50; height: 50 }}]// 狀態切換動畫transitions: Transition {from: "*"to: "fade"reversible: true // 使回退到 normal 狀態也觸發動畫ParallelAnimation {NumberAnimation { properties: "opacity,width,height"; duration: 500 }}}}// 按鈕切換狀態Button {id: toggleButtonanchors.bottom: parent.bottomanchors.horizontalCenter: parent.horizontalCenteranchors.bottomMargin: 20text: box.state === "normal" ? "切換到 fade 狀態" : "切換到 normal 狀態"onClicked: {box.state = box.state === "normal" ? "fade" : "normal";}}}
}
2.4.3 PropertyAnimation(屬性動畫)
功能:用于為任意屬性設置動畫,通常不直接使用,而是用它的子類(如 NumberAnimation,ColorAnimation)。
Rectangle {width: 100; height: 100; color: "red"PropertyAnimation {target: parentproperty: "x"from: 0to: 300duration: 1000running: true}
}
2.4.4 NumberAnimation(數值動畫)
功能:對數值類型的屬性(如 x, y, width, opacity 等)執行線性動畫。
Rectangle {id: boxwidth: 100; height: 100; color: "green"MouseArea {anchors.fill: parentonClicked: {anim.running = true;}}NumberAnimation {id: animtarget: boxproperty: "x"from: 0to: 200duration: 1000running: false}
}
2.4.5 ColorAnimation(顏色動畫)
功能:在顏色值之間平滑過渡。
Rectangle {id: boxwidth: 100; height: 100; color: "blue"MouseArea {anchors.fill: parentonClicked: {colorAnim.running = true;}}ColorAnimation {id: colorAnimtarget: boxproperty: "color"from: "blue"to: "yellow"duration: 800running: false}
}
2.4.6 SequentialAnimation(順序動畫)
作用:
- 依次執行一組動畫。
- 當前動畫執行完畢后,才會開始下一個動畫。
基本語法:
SequentialAnimation {NumberAnimation { target: item; property: "x"; to: 200; duration: 500 }NumberAnimation { target: item; property: "y"; to: 300; duration: 500 }
}
動畫順序:
- 先執行 x 方向移動。
- 然后執行 y 方向移動。
2.4.7 ParallelAnimation(并行動畫)
作用:
- 同時執行一組動畫。
- 所有動畫在同一時間開始。
基本語法:
ParallelAnimation {NumberAnimation { target: item; property: "width"; to: 200; duration: 500 }NumberAnimation { target: item; property: "height"; to: 200; duration: 500 }
}
動畫效果:width 和 height 同時增長。
示例:同時和順序執行動畫
import QtQuick 2.12
import QtQuick.Controls 2.12ApplicationWindow {visible: truewidth: 400height: 400title: "Sequential vs Parallel Animation"Rectangle {id: boxwidth: 50height: 50color: "green"radius: 10x: 20y: 20// 并行動畫:寬高同時變化ParallelAnimation on width {running: falseloops: 1NumberAnimation { to: 150; duration: 500 }NumberAnimation { properties: "height"; to: 150; duration: 500 }}// 順序動畫:先移動X再移動YSequentialAnimation on x {running: falseloops: 1NumberAnimation { to: 200; duration: 500 }NumberAnimation { properties: "y"; to: 200; duration: 500 }}}Row {spacing: 20anchors.bottom: parent.bottomanchors.horizontalCenter: parent.horizontalCenteranchors.bottomMargin: 20Button {text: "執行順序動畫"onClicked: {box.x = 20;box.y = 20;box.x = 200; // SequentialAnimation on x 會觸發}}Button {text: "執行并行動畫"onClicked: {box.width = 50;box.height = 50;box.width = 150; // ParallelAnimation on width 會觸發}}}
}
完整示例
點擊按鈕觸發三種動畫(顏色、大小、位置):
import QtQuick 2.12
import QtQuick.Controls 2.12ApplicationWindow {visible: truewidth: 400height: 300title: qsTr("動畫演示")Rectangle {id: animatedRectwidth: 100height: 100color: "skyblue"radius: 10anchors.centerIn: parent// 動畫狀態切換states: State {name: "moved"when: toggle.checkedPropertyChanges {target: animatedRectx: 200width: 150height: 150color: "tomato"}}// 動畫定義:顏色、尺寸、位置的動畫transitions: Transition {from: "*"to: "moved"reversible: trueParallelAnimation {NumberAnimation { properties: "x,width,height"; duration: 600; easing.type: Easing.OutCubic }ColorAnimation { property: "color"; duration: 600 }}}}// 切換按鈕CheckBox {id: toggleanchors.bottom: parent.bottomanchors.horizontalCenter: parent.horizontalCentertext: "點擊切換動畫"anchors.bottomMargin: 30}
}