Qt Quick编程入门
基于警报应用程序的Qt Quick教程。
本教程介绍如何开发简单的警报应用程序作为Qt Quick和Qt Quick Controls2的简介。
此应用程序类似于通常在Android手机上找到的警报应用程序。其功能使您可以输入,编辑或删除警报。警报可以在给定的日期触发,您可以将其设置为在随后的几天重复一次。
主屏幕显示已保存警报的列表:
详细信息屏幕使您可以编辑或删除现有警报:
对话框屏幕用于添加新警报。当您单击主屏幕底部的“ +” 圆形按钮时,它将弹出:
源文件位于qtdoc存储库中。您可以从Qt项目中获取Qt 5源,也可以将它们作为Qt 5的一部分进行安装。该应用程序也位于Qt Creator的“欢迎”模式的示例列表中。
创建闹钟项目
本节说明如何在Qt Creator中创建项目。它讨论了Qt Creator自动生成的文件,以及程序员必须在Qt Creator或其他一些编辑器中创建的两个文件。后两个文件包含在本教程的源代码中
Qt Creator
在向导的帮助下,可以在Qt Creator中设置新项目,该向导将指导您逐步完成项目创建过程。向导会提示您输入该特定类型的项目所需的设置,并为您创建项目。
要创建Alarms项目,请选择File > New File or Project > Application > Qt Quick Application - Empty > Choose. Type "alarms" in the Name field, 然后按照向导的说明进行操作。
Qt Quick应用程序向导将创建一个包含以下源文件的项目:
Source file | Purpose |
---|---|
alarms.pro | 项目文件 |
main.cpp | 应用程序的主要C ++代码文件。 |
qml.qrc | 资源文件,其中包含源文件的名称,但main.cpp和项目文件除外。 |
该向导在下面的main.cpp文件中生成代码。此代码块启用DPI高缩放,并声明app和engine。然后引擎加载我们的主要QML文件。
int main(int argc, char *argv[]) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
其他源文件
Source file | Purpose |
---|---|
qtquickcontrols2.conf |
选择Material带有Dark主题的样式。 |
main.qml |
链接AlarmDialog.qml,AlarmModel.qml,AlarmDelegate.qml和TumblerDelegate.qml的QML代码 |
AlarmDialog.qml |
定义用于添加新警报的对话框。 |
AlarmDelegate.qml |
定义应用程序主屏幕的布局。 |
AlarmModel.qml |
定义用于存储警报数据的ListModel。 |
TumblerDelegate.qml |
定义玻璃杯的图形布局 |
qtquickcontrols2.conf
以下代码片段显示了如何设置样式的Dark主题Material:
[Controls] Style=Material [Material] Theme=Dark Accent=Red
main.qml
mainWindow
, 一个ApplicationWindow QML类型,是此应用程序中的根项目。
ApplicationWindow {
id: window
width: 400
height: 500
visible: true
The ListView alarmListView
combines the data from alarmModel
with the layout defined in alarmDelegate
.
ListView {
id: alarmListView
anchors.fill: parent
model: AlarmModel {}
delegate: AlarmDelegate {}
}
单击RoundButton 可以添加新警报addAlarmButton
。单击它会打开一个对话框屏幕alarmDialog
。
RoundButton {
id: addAlarmButton
text: "+"
anchors.bottom: alarmListView.bottom
anchors.bottomMargin: 8
anchors.horizontalCenter: parent.horizontalCenter
onClicked: alarmDialog.open()
}
AlarmDialog {
id: alarmDialog
x: Math.round((parent.width - width) / 2)
y: Math.round((parent.height - height) / 2)
alarmModel: alarmListView.model
}
AlarmDialog.qml
This dialog screen has a RowLayout with a Tumbler each for hours and minutes, and another RowLayout with a Tumbler each for day, month, and year.
contentItem: RowLayout {
RowLayout {
id: rowTumbler
Tumbler {
id: hoursTumbler
model: 24
delegate: TumblerDelegate {
text: formatNumber(modelData)
}
}
Tumbler {
id: minutesTumbler
model: 60
delegate: TumblerDelegate {
text: formatNumber(modelData)
}
}
}
RowLayout {
id: datePicker
Layout.leftMargin: 20
property alias dayTumbler: dayTumbler
property alias monthTumbler: monthTumbler
property alias yearTumbler: yearTumbler
readonly property var days: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Tumbler {
id: dayTumbler
function updateModel() {
// Populate the model with days of the month. For example: [0, ..., 30]
var previousIndex = dayTumbler.currentIndex
var array = []
var newDays = datePicker.days[monthTumbler.currentIndex]
for (var i = 1; i <= newDays; ++i)
array.push(i)
dayTumbler.model = array
dayTumbler.currentIndex = Math.min(newDays - 1, previousIndex)
}
Component.onCompleted: updateModel()
delegate: TumblerDelegate {
text: formatNumber(modelData)
}
}
Tumbler {
id: monthTumbler
onCurrentIndexChanged: dayTumbler.updateModel()
model: 12 delegate: TumblerDelegate {
text: window.locale.standaloneMonthName(modelData, Locale.ShortFormat)
}
}
Tumbler {
id: yearTumbler
// This array is populated with the next three years. For example: [2018, 2019, 2020]
readonly property var years: (function() {
var currentYear = new Date().getFullYear()
return [0, 1, 2].map(function(value) { return value + currentYear; })
})()
model: years
delegate: TumblerDelegate {
text: formatNumber(modelData)
}
}
}
}
}
If you click on OK in the dialog, the entered data will be added to alarmModel
:
onAccepted: {
alarmModel.append({
"hour": hoursTumbler.currentIndex,
"minute": minutesTumbler.currentIndex,
"day": dayTumbler.currentIndex + 1,
"month": monthTumbler.currentIndex + 1,
"year": yearTumbler.years[yearTumbler.currentIndex],
"activated": true,
"label": "",
"repeat": false,
"daysToRepeat": [
{ "dayOfWeek": 0, "repeat": false },
{ "dayOfWeek": 1, "repeat": false },
{ "dayOfWeek": 2, "repeat": false },
{ "dayOfWeek": 3, "repeat": false },
{ "dayOfWeek": 4, "repeat": false },
{ "dayOfWeek": 5, "repeat": false },
{ "dayOfWeek": 6, "repeat": false }
],
})
}
onRejected: alarmDialog.close()
AlarmDelegate.qml
Each alarm in the main screen is an ItemDelegate. The ItemDelegate root
contains all fields on the main screen and the detail screen. The detail screen's fields are only visible after an alarm has been clicked on, i.e. when root.checked
is true
.
ItemDelegate {
id: root
width: parent.width
checkable: true
onClicked: ListView.view.currentIndex = index
contentItem: ColumnLayout {
spacing: 0
RowLayout {
ColumnLayout {
id: dateColumn
readonly property date alarmDate: new Date(
model.year, model.month - 1, model.day, model.hour, model.minute)
Label {
id: timeLabel
font.pixelSize: Qt.application.font.pixelSize * 2
text: dateColumn.alarmDate.toLocaleTimeString(window.locale, Locale.ShortFormat)
}
RowLayout {
Label {
id: dateLabel
text: dateColumn.alarmDate.toLocaleDateString(window.locale, Locale.ShortFormat)
}
Label {
id: alarmAbout
text: "⸱ " + model.label
visible: model.label.length > 0 && !root.checked
}
}
}
Item {
Layout.fillWidth: true
}
Switch {
checked: model.activated
Layout.alignment: Qt.AlignTop
onClicked: model.activated = checked
}
}
CheckBox {
id: alarmRepeat
text: qsTr("Repeat")
checked: model.repeat
visible: root.checked
onToggled: model.repeat = checked
}
Flow {
visible: root.checked && model.repeat
Layout.fillWidth: true
Repeater {
id: dayRepeater
model: daysToRepeat
delegate: RoundButton {
text: Qt.locale().dayName(model.dayOfWeek, Locale.NarrowFormat)
flat: true
checked: model.repeat
checkable: true
Material.background: checked ? Material.accent : "transparent"
onToggled: model.repeat = checked
}
}
}
TextField {
id: alarmDescriptionTextField
placeholderText: qsTr("Enter description here")
cursorVisible: true
visible: root.checked
text: model.label
onTextEdited: model.label = text
}
Button {
id: deleteAlarmButton
text: qsTr("Delete")
width: 40
height: 40
visible: root.checked
onClicked: root.ListView.view.model.remove(root.ListView.view.currentIndex, 1)
}
}
}
AlarmModel.qml
This QML file contains the definition of alarmModel
, the ListModel that manages the alarm data.
It creates five ListElements with example alarms.
import QtQuick 2.11
// Populate the model with some sample data.
ListModel {
id: alarmModel
ListElement {
hour: 6
minute: 0
day: 2
month: 8
year: 2018
activated: true
label: "Wake up"
repeat: true
daysToRepeat: [
ListElement { dayOfWeek: 0; repeat: false },
ListElement { dayOfWeek: 1; repeat: false },
ListElement { dayOfWeek: 2; repeat: false },
ListElement { dayOfWeek: 3; repeat: false },
ListElement { dayOfWeek: 4; repeat: false },
ListElement { dayOfWeek: 5; repeat: false },
ListElement { dayOfWeek: 6; repeat: false }
]
}
ListElement {
hour: 6
minute: 0
day: 3
month: 8
year: 2018
activated: true
label: "Wake up"
repeat: true
daysToRepeat: [
ListElement { dayOfWeek: 0; repeat: true },
ListElement { dayOfWeek: 1; repeat: true },
ListElement { dayOfWeek: 2; repeat: true },
ListElement { dayOfWeek: 3; repeat: true },
ListElement { dayOfWeek: 4; repeat: true },
ListElement { dayOfWeek: 5; repeat: false },
ListElement { dayOfWeek: 6; repeat: false }
]
}
[ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { hour: 7 minute: 0 day: 3 month: 8 year: 2018 activated: false label: "Exercise" repeat: true daysToRepeat: [ [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 0; repeat: true }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 1; repeat: true }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 2; repeat: true }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 3; repeat: true }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 4; repeat: true }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 5; repeat: true }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 6; repeat: true } ] } [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { hour: 5 minute: 15 day: 1 month: 9 year: 2018 activated: true label: "" repeat: false daysToRepeat: [ [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 0; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 1; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 2; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 3; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 4; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 5; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 6; repeat: false } ] } [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { hour: 5 minute: 45 day: 3 month: 9 year: 2018 activated: false label: "" repeat: false daysToRepeat: [ [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 0; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 1; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 2; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 3; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 4; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 5; repeat: false }, [ListElement](https://doc.qt.io/qt-5/qml-qtqml-models-listelement.html) { dayOfWeek: 6; repeat: false } ] } }</pre>
TumblerDelegate.qml
TumblerDelegate defines the graphical properties of the Tumblers.
import QtQuick 2.11
import QtQuick.Controls 2.4
import QtQuick.Controls.Material 2.4
Text {
text: modelData
color: Tumbler.tumbler.Material.foreground
font: Tumbler.tumbler.font
opacity: 1.0 - Math.abs(Tumbler.displacement) / (Tumbler.tumbler.visibleItemCount / 2)
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
Entering new alarms
At the bottom of the startup screen, you can see a Button for adding alarms. Click it to open the Add new alarm dialog.
RoundButton {
id: addAlarmButton
text: "+" anchors.bottom: alarmListView.bottom
anchors.bottomMargin: 8
anchors.horizontalCenter: parent.horizontalCenter
onClicked: alarmDialog.open()
}
The dialog for new alarms:
All fields are entered using Tumbler QML types. If you press OK
, the values selected in the Tumblers are written to alarmModel
.
contentItem: RowLayout {
RowLayout {
id: rowTumbler
Tumbler {
id: hoursTumbler
model: 24
delegate: TumblerDelegate {
text: formatNumber(modelData)
}
}
Tumbler {
id: minutesTumbler
model: 60
delegate: TumblerDelegate {
text: formatNumber(modelData)
}
}
}
RowLayout {
id: datePicker
Layout.leftMargin: 20
property alias dayTumbler: dayTumbler
property alias monthTumbler: monthTumbler
property alias yearTumbler: yearTumbler
readonly property var days: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Tumbler {
id: dayTumbler
function updateModel() {
// Populate the model with days of the month. For example: [0, ..., 30]
var previousIndex = dayTumbler.currentIndex
var array = []
var newDays = datePicker.days[monthTumbler.currentIndex]
for (var i = 1; i <= newDays; ++i)
array.push(i)
dayTumbler.model = array
dayTumbler.currentIndex = Math.min(newDays - 1, previousIndex)
}
Component.onCompleted: updateModel()
delegate: TumblerDelegate {
text: formatNumber(modelData)
}
}
Tumbler {
id: monthTumbler
onCurrentIndexChanged: dayTumbler.updateModel()
model: 12
delegate: TumblerDelegate {
text: window.locale.standaloneMonthName(modelData, Locale.ShortFormat)
}
}
Tumbler {
id: yearTumbler
// This array is populated with the next three years. For example: [2018, 2019, 2020]
readonly property var years: (function() {
var currentYear = new Date().getFullYear()
return [0, 1, 2].map(function(value) { return value + currentYear; })
})()
model: years
delegate: TumblerDelegate {
text: formatNumber(modelData)
}
}
}
}
}
Editing alarms
If you click on a particular alarm, you can edit it in the detail screen.
Clicking on an alarm sets root.checked
to true
, which makes visible the fields of the detail screen.
visible: root.checked</pre>
If you want the alarm to trigger also on other days, check alarmRepeat
. The Repeater will display a checkable RoundButton for each day of the week.
[Flow](https://doc.qt.io/qt-5/qml-qtquick-flow.html) {
visible: root.checked && model.repeat
Layout.fillWidth: true
[Repeater](https://doc.qt.io/qt-5/qml-qtquick-repeater.html) {
id: dayRepeater
model: daysToRepeat
delegate: RoundButton {
text: Qt.locale().dayName(model.dayOfWeek, Locale.NarrowFormat)
flat: true
checked: model.repeat
checkable: true
Material.background: checked ? Material.accent : "transparent"
onToggled: model.repeat = checked
}
}
}
If you modify the description of the alarm, it will be reflected in the main screen afterwards.
TextField {
id: alarmDescriptionTextField
placeholderText: qsTr("Enter description here")
cursorVisible: true
visible: root.checked
text: model.label
onTextEdited: model.label = text
}
Deleting alarms
The detail screen (see above) has a Button for deleting alarms. When onClicked
is emitted, the current ListElement is deleted from alarmModel
.
Button {
id: deleteAlarmButton
text: qsTr("Delete")
width: 40
height: 40
visible: root.checked
onClicked: root.ListView.view.model.remove(root.ListView.view.currentIndex, 1)
}
Summary
The app has no code for adding sound or vibration to the alarm, nor does it store the alarms in any format or database. Maybe it could be an interesting coding project to add those features. Adding sound to this program can be realized with Qt Multimedia QML Types. Storing the data could be done quickly and easily in JSON format.