一、Qt Quick应用程序概述
在现代的软件开发中有一个内在的冲突,用户界面的改变速度远远高于我们的后端服务。在传统的技术中我们开发的前端需要与后端保持相同的步调。当一个项目在开发时用户想要改变用户界面,或者在一个项目中开发一个用户界面的想法就会引发这个冲突。敏捷项目需要敏捷的方法。
Qt Quick 提供了一个类似HTML声明语言的环境应用程序作为你的用户界面前端(the front-end),在你的后端使用本地的C++代码。这样允许你在两端都游刃有余。
下面是一个简单的Qt Quick UI的例子:
import QtQuick 2.0
Rectangle {
width: 240; height: 1230
Rectangle {
width: 40; height: 40
anchors.centerIn: parent
color: '#FFBB33'
}
}
这种声明语言被称作QML,它需要在运行时启动。Qt提供了一个典型的运行环境叫做qmlscene,但是想要写一个自定义的允许环境也不是很困难,我们需要一个快速视图(quick view)并且将QML文档作为它的资源。剩下的事情就只是展示我们的用户界面了。
二、QML程序实现
实现了一个简单的窗口程序,在其中居中显示一个红色矩形,矩形中间显示 “hello world” 文字,并且点击矩形区域时会退出程序。
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("QML")
Rectangle {
width: 200
height: 200
color: "red"
anchors.centerIn: parent
Text {
id: text_name
text: qsTr("hello world")
horizontalAlignment: Text.AlignHCenter
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
}
}
QML调用:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
三、QML代码解析
2.1 导入模块部分
import QtQuick 2.12
import QtQuick.Window 2.12
- QtQuick 2.12:导入基础的 QML 类型,如 Rectangle、Text、MouseArea 等。
- QtQuick.Window 2.12:提供 Window 类型,用于创建顶层窗口。
2.2 Window 元素
Window {
visible: true
width: 640
height: 480
title: qsTr("QML")
- Window:一个顶层窗口元素。
- visible: true:窗口启动时可见。
- width/height:窗口大小 640x480。
- title:窗口标题为 “QML”,使用 qsTr() 是为了支持国际化(翻译)。
2.3 Rectangle 矩形元素
Rectangle {
width: 200
height: 200
color: "red"
anchors.centerIn: parent
- Rectangle:创建一个 200x200 的红色矩形。
- color: “red”:矩形填充颜色为红色。
- anchors.centerIn: parent:使该矩形在其父元素 Window 中水平和垂直居中显示。
2.4 Text 文本元素
Text {
id: text_name
text: qsTr("hello world")
horizontalAlignment: Text.AlignHCenter
anchors.centerIn: parent
}
- Text:在矩形中显示文本。
- id: text_name:为该文本对象取名,可用于后续引用。
- text: qsTr(“hello world”):显示内容为 “hello world”,同样支持国际化。
- horizontalAlignment: Text.AlignHCenter:水平方向对齐方式设为居中(注意:对齐生效前提是设置了宽度,否则可以忽略)。
- anchors.centerIn: parent:让文字在矩形中居中。
注意:这里的 parent 是 Rectangle,所以 Text 是居中在红色矩形里。
2.5 MouseArea 鼠标区域
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
- MouseArea:用于处理鼠标交互。
- anchors.fill: parent:填充整个矩形区域,即鼠标点击矩形任何地方都会触发。
- onClicked: Qt.quit():点击后调用 Qt.quit(),程序退出。