QML 基礎語法與對象模型

QML (Qt Meta-Object Language) 是一種聲明式語言,專為創建流暢的用戶界面和應用程序邏輯而設計。作為 Qt 框架的一部分,QML 提供了簡潔、直觀的語法來描述 UI 組件及其交互方式。本文將深入解析 QML 的基礎語法和對象模型。

一、QML 基礎語法

1. 基本對象結構
// 基本矩形對象
Rectangle {id: myRectangle          // 對象標識符width: 200               // 屬性賦值height: 100color: "blue"            // 顏色屬性radius: 10               // 圓角半徑Text {                   // 嵌套對象id: myTexttext: "Hello QML"    // 文本內容color: "white"font.pointSize: 14   // 字體大小anchors.centerIn: parent  // 居中對齊}
}
2. 屬性系統
// 屬性定義與使用
Rectangle {id: containerwidth: 300height: 200color: "lightgray"// 自定義屬性property int count: 0property string status: "就緒"property color textColor: "black"Text {id: statusTexttext: "狀態: " + container.status + ", 計數: " + container.countcolor: container.textColorfont.pointSize: 12anchors.centerIn: parent}// 屬性綁定width: height * 1.5  // 寬度始終是高度的1.5倍// 定時器觸發屬性更新Timer {id: updateTimerinterval: 1000  // 1秒running: truerepeat: trueonTriggered: {container.count += 1if (container.count > 10) {container.status = "完成"container.textColor = "green"updateTimer.running = false}}}
}
3. 信號與槽
// 信號與槽示例
Rectangle {id: buttonwidth: 150height: 50color: "gray"radius: 5// 自定義信號signal clicked// 鼠標區域MouseArea {id: mouseAreaanchors.fill: parentonClicked: button.clicked()  // 觸發自定義信號}// 狀態變化states: [State {name: "pressed"when: mouseArea.pressedPropertyChanges {target: buttoncolor: "darkgray"}}]// 過渡動畫transitions: [Transition {from: ""to: "pressed"reversible: trueColorAnimation {target: buttonproperty: "color"duration: 100}}]
}// 使用自定義按鈕
MyButton {id: myButtonanchors.centerIn: parent// 信號連接onClicked: {console.log("按鈕被點擊了!")// 執行其他操作}
}

二、QML 對象模型

1. 對象層次結構
// 對象層次示例
ApplicationWindow {id: mainWindowvisible: truewidth: 800height: 600title: "QML 對象模型示例"// 菜單欄MenuBar {id: menuBarMenu {title: "文件"MenuItem {text: "打開"onTriggered: console.log("打開文件")}MenuItem {text: "保存"onTriggered: console.log("保存文件")}}Menu {title: "編輯"// 菜單項...}}// 主內容區Rectangle {id: contentAreaanchors {top: menuBar.bottomleft: parent.leftright: parent.rightbottom: parent.bottom}color: "white"// 列表視圖ListView {id: itemListanchors.fill: parentmodel: ["項目1", "項目2", "項目3", "項目4", "項目5"]delegate: Rectangle {height: 40width: parent.widthcolor: index % 2 === 0 ? "lightgray" : "white"Text {text: modelDataanchors.verticalCenter: parent.verticalCenteranchors.left: parent.leftanchors.leftMargin: 10}}}}
}
2. 數據模型與視圖
// 數據模型與視圖示例
Rectangle {id: mainContainerwidth: 400height: 300color: "lightblue"// 列表模型ListModel {id: contactModelListElement {name: "張三"phone: "13800138000"favorite: true}ListElement {name: "李四"phone: "13900139000"favorite: false}ListElement {name: "王五"phone: "13700137000"favorite: true}}// 列表視圖ListView {id: contactListanchors.fill: parentmodel: contactModeldelegate: Item {width: parent.widthheight: 50Rectangle {anchors.fill: parentcolor: favorite ? "lightgreen" : "white"Text {text: namefont.pointSize: 14anchors.left: parent.leftanchors.leftMargin: 10anchors.verticalCenter: parent.verticalCenter}Text {text: phonefont.pointSize: 12color: "gray"anchors.right: parent.rightanchors.rightMargin: 10anchors.verticalCenter: parent.verticalCenter}}}}
}
3. 組件化與模塊化
// 創建自定義組件 (MyButton.qml)
import QtQuick 2.15Rectangle {id: buttonwidth: 120height: 40color: "blue"radius: 5border.width: 1border.color: "darkblue"property string text: "按鈕"property color hoverColor: "lightblue"property color pressedColor: "darkblue"signal clickedText {id: buttonTexttext: button.textcolor: "white"font.pointSize: 12anchors.centerIn: parent}MouseArea {id: mouseAreaanchors.fill: parenthoverEnabled: trueonEntered: button.color = button.hoverColoronExited: button.color = "blue"onPressAndHold: button.color = button.pressedColoronClicked: button.clicked()}
}// 使用自定義組件
import QtQuick 2.15
import QtQuick.Window 2.15Window {id: mainWindowvisible: truewidth: 400height: 300title: "組件化示例"MyButton {id: loginButtontext: "登錄"anchors.centerIn: parentonClicked: console.log("登錄按鈕被點擊")}MyButton {id: cancelButtontext: "取消"anchors {bottom: loginButton.topbottomMargin: 20horizontalCenter: loginButton.horizontalCenter}color: "red"hoverColor: "lightred"pressedColor: "darkred"onClicked: console.log("取消按鈕被點擊")}
}

三、QML 與 JavaScript 交互

1. JavaScript 表達式
// JavaScript 表達式示例
Rectangle {id: calculatorwidth: 300height: 200color: "white"property int num1: 10property int num2: 20property int result: 0Text {id: resultTexttext: "計算結果: " + calculator.resultfont.pointSize: 14anchors.centerIn: parent}Row {anchors {bottom: parent.bottomhorizontalCenter: parent.horizontalCenterbottomMargin: 20}spacing: 10Button {text: "加法"onClicked: calculator.result = calculator.num1 + calculator.num2}Button {text: "減法"onClicked: calculator.result = calculator.num1 - calculator.num2}Button {text: "乘法"onClicked: calculator.result = calculator.num1 * calculator.num2}}
}
2. JavaScript 函數
// JavaScript 函數示例
Rectangle {id: validationFormwidth: 400height: 250color: "lightgray"property string username: ""property string password: ""property bool isValid: falseTextField {id: usernameFieldplaceholderText: "用戶名"width: 200anchors {horizontalCenter: parent.horizontalCentertop: parent.toptopMargin: 30}onTextChanged: validationForm.username = text}TextField {id: passwordFieldplaceholderText: "密碼"width: 200echoMode: TextField.Passwordanchors {horizontalCenter: parent.horizontalCentertop: usernameField.bottomtopMargin: 20}onTextChanged: validationForm.password = text}Text {id: validationTexttext: validationForm.isValid ? "驗證通過" : "請輸入用戶名和密碼"color: validationForm.isValid ? "green" : "red"anchors {horizontalCenter: parent.horizontalCentertop: passwordField.bottomtopMargin: 20}}Button {text: "驗證"anchors {horizontalCenter: parent.horizontalCenterbottom: parent.bottombottomMargin: 30}onClicked: validateForm()}// JavaScript 函數function validateForm() {if (username.length >= 3 && password.length >= 6) {isValid = trueconsole.log("表單驗證通過")} else {isValid = falseconsole.log("表單驗證失敗")}}
}

四、QML 動畫與過渡

1. 基本動畫
// 動畫示例
Rectangle {id: animatedRectwidth: 100height: 100color: "red"x: 50y: 50// 位置動畫NumberAnimation {id: moveAnimationtarget: animatedRectproperty: "x"to: 250duration: 1000easing.type: Easing.InOutQuadloops: Animation.Infiniterunning: true}// 顏色動畫ColorAnimation {id: colorAnimationtarget: animatedRectproperty: "color"from: "red"to: "blue"duration: 2000loops: Animation.Infiniterunning: true}
}
2. 狀態與過渡
// 狀態與過渡示例
Rectangle {id: toggleButtonwidth: 100height: 50color: "gray"radius: 25property bool checked: falseRectangle {id: handlewidth: 40height: 40color: "white"radius: 20x: checked ? 55 : 5y: 5}MouseArea {anchors.fill: parentonClicked: {toggleButton.checked = !toggleButton.checked}}states: [State {name: "checked"when: toggleButton.checkedPropertyChanges {target: toggleButtoncolor: "green"}PropertyChanges {target: handlex: 55}}]transitions: [Transition {from: ""to: "checked"reversible: trueNumberAnimation {target: handleproperty: "x"duration: 300easing.type: Easing.InOutQuad}ColorAnimation {target: toggleButtonproperty: "color"duration: 300}}]
}

五、總結

QML 提供了一種直觀、高效的方式來創建現代化的用戶界面:

  1. 聲明式語法:通過簡潔的語法描述 UI 組件和屬性關系。
  2. 對象模型:基于層次結構的對象系統,支持嵌套和組合。
  3. 屬性系統:強大的屬性綁定機制,實現數據驅動的 UI 更新。
  4. 信號與槽:事件處理機制,支持組件間通信。
  5. 組件化:支持創建可復用的自定義組件,提高開發效率。
  6. 動畫系統:內置多種動畫類型,輕松實現流暢的視覺效果。

通過掌握 QML 的基礎語法和對象模型,開發者可以快速構建出美觀、交互性強的應用界面,同時利用 Qt 的跨平臺能力,實現一次開發多平臺部署。

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

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

相關文章

HTTPS的概念和工作過程

一.HTTPS是什么HTTPS也是一個應用層協議,是在HTTP協議的基礎上引入了一個加密層(SSL)HTTP協議內容都是按照文本的方式明文傳輸的,這就導致傳輸過程中可能出現被篡改的情況最著名的就是十多年前網絡剛發展的時期,出現“…

Unity —— Android 應用構建與發布?

文章目錄1 ?Gradle模板??:了解Gradle模板的作用及使用方法,以增強對構建流程的控制。?2 ?Gradle模板變量??:參考文檔——自定義Gradle模板文件中可用的變量列表。2.1 修改Unity應用的Gradle工程文件2.1.1 通過Gradle模板文件2.1.2 導出…

【iOS】strong和copy工作流程探尋、OC屬性關鍵字復習

文章目錄前言strong和copy的區別為什么要用copy?什么時候用什么修飾?strong(ARC自動管理)strong修飾變量的底層流程圖底層代碼核心實現小結copy底層流程圖對比與strong的關鍵不同之處內部調用關系(偽代碼)小…

程序代碼篇---多循環串口程序切換

上位機版(Python)要實現根據串口接收結果高效切換四個 while 循環函數,我們可以采用狀態機模式,配合非阻塞串口讀取來設計程序結構。這種方式可以實現快速切換,避免不必要的資源消耗。下面是一個高效的實現方案&#x…

rk3568上,實現ota,計算hash,驗證簽名,判斷激活分區,并通過dd命令,寫入對應AB分區

通過自定義升級程序&#xff0c;更直觀的理解ota升級原理。 一、模擬計算hash&#xff0c;驗證簽名&#xff0c;判斷激活分區&#xff0c;并通過dd命令&#xff0c;寫入對應分區 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <u…

數據分析—numpy庫

numpy庫NumPy 庫全面指南NumPy (Numerical Python) 是 Python 科學計算的基礎庫&#xff0c;提供了高性能的多維數組對象和工具。以下是 NumPy 的核心功能和使用方法。一、安裝與基礎1. 安裝 NumPypip install numpy2. 導入 NumPyimport numpy as np # 標準導入方式二、數組創建…

Vue3 setup、ref和reactive函數

一、setup函數1.理解&#xff1a;Vue3.0中一個新的配置項&#xff0c;值為一個函數。2.setup是所有Composition API(組合API)的“表演舞臺”。3.組件中用到的&#xff1a;數據、方法等等&#xff0c;均要配置在setup中。4.setup函數的兩種返回值&#xff1a;(1).若返回一個對象…

python中appium 的NoSuchElementException錯誤 原因以及解決辦法

錯誤收集D:\Program\Util\python.exe "D:/Program/myUtil/PyCharm 2024.3.5/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py" --target demo.py::TestAppium Testing started at 15:57 ... Launching pytest with arguments demo.py::TestAppium --no-hea…

mybatis-plus從入門到入土(四):持久層接口之BaseMapper和選裝件

大家好&#xff0c;今天繼續更新MybatisPlus從入門到入土系列&#xff0c;上一次的持久層接口還沒講完&#xff0c;只講了IService接口&#xff0c;今天我們繼續來講一下。 BaseMapper BaseMapper中的方法也比較簡單&#xff0c;都是增刪改查的基礎API&#xff0c;不知道大家還…

數組和指針的關系

在 C 語言中&#xff0c;?指針和數組有著非常緊密的聯系&#xff0c;但它們本質上是 ?不同的概念。理解它們的關系是掌握 C 語言內存操作的關鍵。下面我會從多個角度幫你梳理 ?指針和數組的直接聯系&#xff0c;并解釋它們的異同點。1. 數組和指針的本質區別?概念本質存儲方…

AI大模型探索之路-實戰篇:智能化IT領域搜索引擎之github網站在線搜索

系列篇章?? No. 文章 1 AI大模型探索之路-實戰篇:智能化IT領域搜索引擎的構建與初步實踐 2 AI大模型探索之路-實戰篇:智能化IT領域搜索引擎之GLM-4大模型技術的實踐探索 3 AI大模型探索之路-實戰篇:智能化IT領域搜索引擎之知乎網站數據獲取(初步實踐) 4 AI大模型探索之路…

從0到1學PHP(十二):PHP 框架入門與項目實戰

目錄一、主流 PHP 框架介紹1.1 Laravel1.2 ThinkPHP1.3 Yii1.4 框架的優勢二、框架基本使用&#xff08;以 Laravel 為例&#xff09;2.1 框架的安裝與配置2.2 路由定義、控制器創建、視圖渲染2.3 數據庫操作&#xff08;ORM 的使用&#xff09;三、小型項目實戰3.1 項目需求分…

MPLS LSP

一、概述上一章我們已經介紹過,LSP是MPLS報文在MPLS網絡中轉發時經過的路徑,可以看作是由報文傳輸方向節點為對應FEC分配的MPLS入標簽組成的,因為每臺設備上為每個FEC分配的入標簽是唯一 的&#xff0c;并與由下游節點為本地節點上該FEC分配的出標簽建立映射關系&#xff0c; 所…

圖像、視頻、音頻多模態大模型中長上下文token壓縮方法綜述

多模態大模型MLLMs 能夠處理高分辨率圖像、長視頻序列和冗長音頻輸入等復雜上下文&#xff0c;但自注意力機制的二次復雜度使得大量輸入 token 帶來了巨大的計算和內存需求。 如下圖&#xff0c;上&#xff1a;圖像、視頻和音頻數據類型可以在其表示維度上進行擴展&#xff0c;…

Spring MVC 九大組件源碼深度剖析(一):MultipartResolver - 文件上傳的幕后指揮官

文章目錄一、為什么從 MultipartResolver 開始&#xff1f;二、核心接口&#xff1a;定義文件上傳的契約三、實現解析&#xff1a;兩種策略的源碼較量1. StandardServletMultipartResolver&#xff08;Servlet 3.0 首選&#xff09;2. CommonsMultipartResolver&#xff08;兼容…

stm32是如何實現電源控制的?

STM32的電源控制主要通過內置的電源管理模塊&#xff08;PWR&#xff09;實現&#xff0c;涵蓋電壓調節、功耗模式切換和電源監控等功能。以下是其核心機制及實現方式&#xff1a;??1. 電源架構與供電區域??STM32的電源系統分為多個供電區域&#xff0c;各司其職&#xff1…

《R for Data Science (2e)》免費中文翻譯 (第3章) --- Data transformation(1)

寫在前面 本系列推文為《R for Data Science (2)》的中文翻譯版本。所有內容都通過開源免費的方式上傳至Github&#xff0c;歡迎大家參與貢獻&#xff0c;詳細信息見&#xff1a; Books-zh-cn 項目介紹&#xff1a; Books-zh-cn&#xff1a;開源免費的中文書籍社區 r4ds-zh-cn …

rclone、rsync、scp使用總結

數據同步工具使用總結【rclone、rsync、scp】一、數據處理背景二、數據處理方法對比1、數據關系梳理2、不同工具處理方法3、經驗總結三、工具擴展知識1、rclone工具介紹&#xff08;1&#xff09;、rclone概述&#xff08;2&#xff09;、安裝工具及配置本地文件遷移到云上服務…

用latex+vscode+ctex寫畢業論文

文章目錄前言一、安裝latex二、安裝ctex包三、更新ctex包四、使用ctex文檔類前言 用latexvscodectex寫畢業論文。&#xff08;英文論文不用安裝ctex&#xff09; CTEX 宏集是面向中文排版的通用 LATEX 排版框架&#xff0c;為中文 LATEX 文檔提供了漢字輸出支持、標點壓縮、字…

深度學習·mmsegmentation基礎教程

mmsegmentation的使用教程 mmsegmentation微調方法總結 自定義自己的數據集&#xff1a;mmsegmentation\configs\_base_\datasets\ZihaoDataset_pipeline.py注冊&#xff1a;mmsegmentation\configs\_base_\datasets\__init__.py定義訓練和測試的pipeline&#xff1a;mmsegme…