QML開發:QML中的基本元素

文章目錄

    • 一、概述
    • 二、常用基本元素
      • 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}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/92353.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/92353.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/92353.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Spring AI 項目實戰(二十二):Spring Boot + AI +DeepSeek實現智能合同數據問答助手?(附完整源碼)

系列文章 序號 文章名稱 1 Spring AI 項目實戰(一):Spring AI 核心模塊入門 2 Spring AI 項目實戰(二):Spring Boot + AI + DeepSeek 深度實戰(附完整源碼) 3 Spring AI 項目實戰(三):Spring Boot + AI + DeepSeek 打造智能客服系統(附完整源碼) 4

從 0 到 1 創建 InfluxDB 3 表:標簽、字段、命名規范一篇講透

前言 在使用 InfluxDB 3 存儲時序數據時,表的設計堪比蓋房子打地基,地基打歪,數據“塌方”指日可待。InfluxDB 雖然不是傳統意義上的關系型數據庫,但它有自己的一套“審美”:標簽(Tags)和字段(Fields)是它的雙核心,誰先誰后,關系重大,順序寫錯,查詢性能立馬打折。…

[sqlserver] 分析SQL Server中執行效率較低的SQL語句

查詢性能分析較低的SQL語句 -- 查詢性能分析 SELECT TOP 50qs.creation_time AS [編譯時間],qs.last_execution_time AS [最后執行時間],qs.execution_count AS [執行次數],qs.total_worker_time/1000 AS [CPU總時間(ms)],qs.total_elapsed_time/1000 AS [總耗時(ms)],(qs.tota…

SmartX 用戶建云實踐|寶信軟件:搭建“雙架構”私有云平臺,靈活滿足多種業務需求

上海寶信軟件股份有限公司&#xff08;以下簡稱寶信軟件&#xff09;系中國寶武實際控制、寶鋼股份控股的上市軟件企業&#xff0c;是中國領先的工業軟件行業應用解決方案和服務提供商&#xff0c;為寶武集團提供整體 IT 基礎架構解決方案與服務。為統一管理寶武集團旗下分散在…

應用科普 | 漫談6G通信的未來

【摘要前言】2019年推出的5G無線通信將移動設備的性能提升到了一個新的水平。首批應用利用5G提供移動寬帶&#xff0c;使消費者能夠以遠超以往的速度進行流媒體傳輸、游戲和連接。隨著技術的成熟&#xff0c;它已成為物聯網的關鍵組成部分&#xff0c;將機器匯集到一個全球網絡…

從零開始用 Eclipse 寫第一個 Java 程序:HelloWorld 全流程 + 避坑指南

對于 Java 初學者來說&#xff0c;第一次用 Eclipse 寫程序往往會手足無措 —— 找不到新建項目的入口、不知道包和類該怎么命名、運行時控制臺突然消失…… 別慌&#xff01;本文以最經典的 “HelloWorld” 為例&#xff0c;手把手帶你走完從 Eclipse 項目創建到程序運行的完整…

NVIDIA Isaac GR00T N1.5 源碼剖析與復現

? 0. 前言 2025.6.11 NVIDIA Isaac GR00T N1 進化&#xff0c;英偉達發布了NVIDIA Isaac GR00T N1.5模型&#xff0c;效果比原先提高了不少&#xff0c;故來復現一下&#xff0c;看看能否應用于我的項目中&#xff1a; 代碼頁 項目頁 模型頁 ? 以下是使用 GR00T N1.5 的一般…

手把手教你馴服Apache IoTDB時序數據庫,開啟時序數據管理新征程!

手把手教你馴服Apache IoTDB&#xff0c;開啟時序數據管理新征程&#xff01; 本文是一篇幽默風趣的 Apache IoTDB 時序數據庫安裝使用教程。從 “這東西能不能吃” 的靈魂拷問切入&#xff0c;先科普 IoTDB 的 “真實身份”—— 一款專為時序數據設計的數據庫利器&#xff0c;…

劇本殺小程序系統開發:開啟沉浸式推理社交新紀元

在數字化浪潮席卷的當下&#xff0c;傳統娛樂方式正經歷著前所未有的變革&#xff0c;劇本殺這一融合了推理、角色扮演與社交互動的熱門游戲&#xff0c;也搭上了科技的快車&#xff0c;劇本殺小程序系統開發應運而生&#xff0c;為玩家們開啟了一扇通往沉浸式推理社交新世界的…

Ubuntu系統VScode實現opencv(c++)視頻的處理與保存

通過OpenCV等計算機視覺工具&#xff0c;開發者可以像處理靜態圖像一樣對視頻流逐幀分析&#xff1a;從簡單的裁剪、旋轉、色彩校正&#xff0c;到復雜的穩像、目標跟蹤、超分辨率重建。而如何將處理后的高幀率、高動態范圍數據高效壓縮并封裝為通用格式&#xff08;如MP4、AVI…

三坐標測量技術解析:從基礎原理到斜孔測量難點突破

基礎原理 三坐標測量儀&#xff08;Coordinate Measuring Machine&#xff0c;CMM&#xff09;這種集機械、電子、計算機技術于一體的三維測量設備&#xff0c;其核心技術原理在于&#xff1a;當接觸式或非接觸式測頭接觸感應到工件表面時&#xff0c;測量系統會瞬間記錄三個坐…

【MySQL基礎篇】:MySQL常用內置函數以及實用示例

?感謝您閱讀本篇文章&#xff0c;文章內容是個人學習筆記的整理&#xff0c;如果哪里有誤的話還請您指正噢? ? 個人主頁&#xff1a;余輝zmh–CSDN博客 ? 文章所屬專欄&#xff1a;MySQL篇–CSDN博客 文章目錄內置函數一.日期函數二.字符串函數三.數學函數四.其他函數內置函…

Mirror學習筆記

Mirror官方案例操作 一、導入Mirror 在unity商城訂閱Mirror https://assetstore.unity.com/packages/tools/network/mirror-129321 使用unity創建工程 &#xff08;推薦版本&#xff1a;目前建議使用 Unity 2020 或 2021 LTS 版本&#xff1b;超出這些版本的可能可以運行…

R4周打卡——Pytorch實現 LSTM火災預測

&#x1f368; 本文為&#x1f517;365天深度學習訓練營 中的學習記錄博客&#x1f356; 原作者&#xff1a;K同學啊 一、準備工作 1.1導入數據 1.2數據集可視化 二、構建數據集 2.1數據集預處理 2.2設置X、Y 2.3檢查數據集中有沒有空值 2.4劃分數據集 三、構建模型 3.1定義訓…

【視覺識別】Ubuntu 22.04 上編譯安裝OPENCV 4.12.0 魯班貓V5

系列文章目錄 提示&#xff1a;這里可以添加系列文章的所有文章的目錄&#xff0c;目錄需要自己手動添加 例如&#xff1a;第一章 Python 機器學習入門之pandas的使用 提示&#xff1a;寫完文章后&#xff0c;目錄可以自動生成&#xff0c;如何生成可參考右邊的幫助文檔 文章目…

基于vue的財務管理系統/基于php的財務管理系統

基于vue的財務管理系統/基于php的財務管理系統

機器學習技術在訂單簿大單檢測中的應用研究

訂單簿數據的特點 訂單簿&#xff08;Order Book&#xff09;是記錄市場上所有未成交買賣訂單的數據結構&#xff0c;通常包括價格、數量、買賣方向等信息。訂單簿數據具有以下特點&#xff1a; 高頻率&#xff1a;訂單簿數據更新速度極快&#xff0c;通常以毫秒甚至微秒為單位…

Spring MVC框架中DispatcherServlet詳解

1. DispatcherServlet概述1.1 什么是DispatcherServlet&#xff1f;DispatcherServlet是Spring MVC框架的核心組件&#xff0c;它本質上是一個Java Servlet&#xff0c;作為前端控制器(Front Controller)負責接收所有HTTP請求&#xff0c;并根據特定規則將請求分發到相應的處理…

DBA急救手冊:拆解Oracle死鎖圖,ORA-00060錯誤秒級定位終極指南

關于“死鎖圖”&#xff08;Deadlock Graph&#xff09;的一點淺見 當 Oracle 檢測到死鎖時&#xff0c;檢測到死鎖的會話中的當前 SQL 將被取消&#xff0c;并執行“語句級回滾”&#xff0c;以釋放資源并避免阻塞所有活動。 檢測到死鎖的會話仍然“存活”&#xff0c;并且事務…

C++中的默認函數學習

今天在學習QT別人的項目時看到有個函數在聲明和調用時參數個數不一樣&#xff0c;查了下是c中的一種函數類型&#xff0c;這個類型的函數可以讓代碼更簡潔、靈活。定義&#xff1a;在函數聲明時&#xff0c;給某些參數預先設定一個默認值。調用函數時&#xff0c;如果省略這些參…