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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈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…