QT - Qt Quick编程入门

Qt Quick编程入门

基于警报应用程序的Qt Quick教程。

本教程介绍如何开发简单的警报应用程序作为Qt Quick和Qt Quick Controls2的简介。

此应用程序类似于通常在Android手机上找到的警报应用程序。其功能使您可以输入,编辑或删除警报。警报可以在给定的日期触发,您可以将其设置为在随后的几天重复一次。

主屏幕显示已保存警报的列表:

"Alarms application"

详细信息屏幕使您可以编辑或删除现有警报:

"Detail screen"

对话框屏幕用于添加新警报。当您单击主屏幕底部的“ +” 圆形按钮时,它将弹出:

"Add alarms"

源文件位于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 Creator New File or Project dialog"
"Project Location"

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:

"Add 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.

image

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.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容