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 提供了一種直觀、高效的方式來創建現代化的用戶界面:
- 聲明式語法:通過簡潔的語法描述 UI 組件和屬性關系。
- 對象模型:基于層次結構的對象系統,支持嵌套和組合。
- 屬性系統:強大的屬性綁定機制,實現數據驅動的 UI 更新。
- 信號與槽:事件處理機制,支持組件間通信。
- 組件化:支持創建可復用的自定義組件,提高開發效率。
- 動畫系統:內置多種動畫類型,輕松實現流暢的視覺效果。
通過掌握 QML 的基礎語法和對象模型,開發者可以快速構建出美觀、交互性強的應用界面,同時利用 Qt 的跨平臺能力,實現一次開發多平臺部署。