June 2017: Introduction to Qt

Introduction to qt

By Charles Calkins, OCI Principal Software Engineer

JUNE 2017

Introduction

Qt (pronounced "cute") is a cross-platform framework for creating applications. It was originally conceived in 1990, with its first public release in 1995 for Linux. Over time, it developed support for embedded devices, such as cell phones, through desktop platforms, such as Windows and Mac OS X. This article describes the basics of creating a basic calculator application using Qt that can run on multiple devices.

Obtaining Qt

Qt is available both in Open Source and commercial versions. While the Open Source version may be used to develop applications, a commercial license is required for the development of commercial software where compliance with the GNU Lesser Public License (LGPL) is not possible. The commercial distribution also provides more optimized code in certain circumstances, as well as additional Qt software components that are not available in the Open Source distribution.

Two major flavors exist — Qt for desktop and mobile applications, and Qt for embedded devices. For this article, version 5.8 of Qt for desktop and mobile applications is used.

While the source code for Qt may be downloaded and compiled manually, distributions of Qt may be obtained via a unified installer or by downloading platform-specific archives.

Archives are selected by the host architecture, such as Windows or Linux, and then by the platform to compile for.

A compiler toolchain is known as a kit, and multiple kits may be installed on the same machine. For instance, distributions available for a Windows host at the time of this writing include 32- and 64-bit distributions for Visual Studio 2013 and 2015, and 32-bit distributions for MinGW, WinRT with Visual Studio 2013 and 2015, and Android. With Mac OS X as the host, distributions that use Clang are available for Mac OS X, as well as iOS development. Linux distributions may use compilers such as GCC.

The main integrated development environment for Qt is Qt Creator, provided as part of the distribution. It provides an editor and debugger, as well as a kit management system to configure and allocate kits to the projects that they will compile.

Qt also provides a large library of example code and an extensive help system. Qt Creator's editor also provides helpful code editing features, such as method refactoring, underlining of unused variables, and other features expected from a modern editor.

QML Calc

To illustrate Qt, in this article we'll develop a basic calculator, inspired by code written in Java by Fred Swartz.

Prior to relatively recent versions of Qt, a Qt application had to be created completely in C++, but with the development of QML, the Qt Meta (or Markup) Language, the user interface may be developed independently in a special scripting language.

UI constructs are declared in QML, and behavior is implemented in JavaScript, meaning a workable Qt application can be written almost entirely without the need for C++. Our first version of the calculator will be implemented in this manner.

In Qt Creator, a new QML-enabled project may be created by selecting New Project -> Application -> Qt Quick Application. For this example, we'll uncheck the checkbox in the project creation options and not generate a ui.qml file (useful for using a provided UI layout editor) in order to more easily view how QML operates. The QML skeleton code that is generated creates a clickable window containing a text field, as follows, in the file main.qml:

QML code begins with import statements, each typically naming a Qt module and the version number of the module that is being imported. A difference in recent versions of Qt, for example, are version 1 vs. version 2 controls. While version 1 controls are still available for use, version 2 controls are richer and more performant and have a somewhat different syntax than version 1 controls.

QML supports a number of GUI elements. A Window is one that represents a basic application window. QML, with respect to layout, is hierarchical; after properties such as size and visibility are set (using the property name : property value syntax), the next elements are GUI elements contained within the Window.

A MouseArea represents a clickable area. GUI elements are positioned in various ways, with this one filling its parents by anchoring all four of its sides to the sides of its parent, using the .fill shortcut. So, no matter where one clicks in the Window, the onClicked handler will be invoked. Handlers are implemented in JavaScript, either inline, as in this case, or by calling a JavaScript function defined elsewhere. Here, clicking causes a message to be logged to the console. Qt supports internationalization via the call qsTr(), although internationalization is not fully realized in this code skeleton.

A TextEdit element provides a means for text entry. The id property is used to identify an element for referencing elsewhere — here, the id is set to textEdit so its text property, the contents of the edit field, may be logged to the console on a mouse click. As with the MouseArea element, the TextEdit element is also positioned via anchors; but instead of filling its parent, it is set such that the top of the edit control is 20 pixels below the top of the parent window (via the top and topMargin anchor properties), and is centered horizontally. The Rectangle within the TextEdit element allows the look of the TextEdit element to be customized. Here, the rectangle is as large as the TextEdit element itself (via the anchors.fill: parent setting), and is drawn with a 1 pixel outline and transparent background.

The skeleton code generation also creates a minimal C++ file to load the QML in main.cpp:

#include <QGuiApplication>

#include <QQmlApplicationEngine>

int main(int argc, char*argv[])

{

QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;

engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

return app.exec();

}

This code creates a QGuiApplication, loads the QML file into a QQmlApplicationEngine, and then starts the application message loop by calling app.exec().

For the calculator example, we shall leave the C++ code unchanged, but erase the contents of main.qml and start fresh. The source code for this article is available in the accompanying code archive, and is described below.

We begin by importing various QML modules, and as the skeleton code did, we create a Window:

import QtQuick 2.6

import QtQuick.Window 2.2

import QtQuick.Controls 2.1

import QtQuick.Layouts 1.3

Window {

visible: true

width: 640

height: 480

title: qsTr("Calculator")

Next, reminiscent of the original Java code, we create several variables to store the state of the calculator. We use the property syntax to define them as custom properties of the window.

property double currentTotal: 0

property bool startNumber: true

property string displayField: "0"

property string previousOp: "="

property string error: qsTr("ERROR")

The behavior of the calculator is implemented by a series of JavaScript functions that parallel the original Java, such as:

function applyOp(op) {

if (startNumber) {

clear();

displayField = error; // expecting a number

} else {

startNumber = true;

if (previousOp === "=")

setTotal(displayField);

else if (previousOp === "+")

add(displayField);

else if (previousOp === "-")

subtract(displayField);

else if (previousOp === "*")

multiply(displayField);

else if (previousOp === "/")

divide(displayField);

displayField = getTotal().toString();

previousOp = op;

}

}

Individual methods perform the calculator mathematics, with applyOp() called when a user enters an operator, applyDigit() invoked when the user enters a digit, and other methods as appropriate.

As we want the calculator to consist of a display where one may see digits entered and the results of calculations above a set of buttons, we use a ColumnLayout to place the display field above the buttons. The ColumnLayout fills the entire parent window (the Window), and the display anchors itself to the left and right of the parent window so it will expand and contract as the window does. It does not need to anchor itself to the top of the window as the ColumnLayout manages its vertical position. The font is increased from the default via the font properties.

ColumnLayout {

anchors.fill: parent

TextEdit {

id: textEdit

text: displayField

verticalAlignment: Text.AlignVCenter

horizontalAlignment: Text.AlignRight

anchors.left: parent.left

anchors.right: parent.right

color: "#000000"

font.family: "Abel"

font.pointSize: 16

anchors.margins: 10

Rectangle {

anchors.fill: parent

color: "transparent"

border.width: 1

}

}

Below the display are the calculator buttons, arranged by using a GridLayout. That is, the ColumnLayout aligns two UI elements, a TextEdit above a GridLayout. The GridLayout is set to have four rows and four columns, and it, too, is anchored to the left and right sides of the display.

GridLayout {

id: grid

rows: 4

columns: 4

anchors.left: parent.left

anchors.right: parent.right

GridButton {

text: "CE"

onClicked: clearEntry()

}

GridButton {

text: "C"

onClicked: clear()

}

The GridLayout contains 16 different GridButtons, where a GridButton is a custom element. Custom elements may be defined by creating additional QML files that have the same name as the element that is being defined. In our case, the file GridButton.qml contains the following definition:

import QtQuick 2.0

import QtQuick.Controls 2.1

import QtQuick.Layouts 1.3

Button {

Layout.fillHeight: true

Layout.fillWidth: true

contentItem: Text {

renderType: Text.NativeRendering

verticalAlignment: Text.AlignVCenter

horizontalAlignment: Text.AlignHCenter

font.family: "Abel"

font.pointSize: (parent.width > 0) ? parent.width/5 : 14

text: parent.text

}

}

The file is written to be self-contained in that it, too, begins with import statements and contains QML elements. The Button element represents a pushbutton, and as it is placed in a GridLayout, has Layout-related properties that can be set. The fillHeight and fillWidth properties allow the buttons to expand to fill the grid cells, so as the window changes size, so do the grid buttons. The contentItem of the button is Text, as the buttons will display numbers, operators, or other symbols. The pointSize of the text adjusts based on the window size, but care must be taken to not resize the window too rapidly as the author has seen instances where the application will crash if the window refreshes too quickly. If the pointSize is set to a constant value, the crashes do not occur.

Returning to main.qml, one sees that if every GridButton were the full Button definition, the code may become too complex and repetitive to maintain. Moving common settings out into user-defined objects makes the code much cleaner. Properties not specified in common, such as the text property representing the characters to show on the button, are set on each button individually. Incidentally, QML supports Unicode, so special characters, such as the left arrow symbol, may be represented.

GridButton {

text: "\u2190" // "<-"

onClicked: backspace()

}

C++ Calc

While much may be done in QML with JavaScript, applications often need functionality that may not be provided by the Javascript implementation. QML may interact with C++ in a relatively straightforward way. In this example, we move the functionality that was implemented in JavaScript to C++ in order to demonstrate the interactivity.

Qt's support for C++ is extensive. In order to provide its multi-platform capability, Qt includes many classes to isolate the application from the underlying operating system. These types range from basic entities such as QString and QList through more complex ones that manage Bluetooth connectivity, socket and serial port access, database queries, and the like. By using what Qt provides, as well as portable C++ constructs, an application may compile on any Qt-supported platform without modification.

We need to create a C++ object which may be referenced by QML, and as the base class for many Qt objects is QObject, we must inherit from it as well. The Q_OBJECT macro must also be specified so various Qt support functions may be declared. Since the object we need to create supports calculator functions, we'll call it Calc, defined in calc.h and calc.cpp.

#ifndef CALC_H

#define CALC_H

#include <QObject>

#include <QQmlApplicationEngine>

#include <QString>

class Calc :public QObject

{

Q_OBJECT

Only one variable is needed that must be in common between C++ and QML — the calculator display. It is defined as a Q_PROPERTY so the correct annotations may be made automatically to allow the field to be accessible. Part of the build process of a Qt application runs a preprocessor that generates additional code in files prefixed by moc_ based on macros, such as these to provide the runtime type support, message passing, and QML connectivity.

A Q_PROPERTY need not always specify read, write, or notification methods. For example, a property may only have a read method and be declared CONSTANT if the property does not change during runtime of the application. For this calculator example, the read and write methods are standard getters and setters implemented in calc.cpp, and displayFieldChanged() is a signal, a special Qt construct used for message passing, identified by the special signals: section in a class definition. A signal may be explicitly attached to a slot, a signal handler function, by the QObject::connect() method; or as happens here, is implicitly associated with QML where QML code that uses the property will automatically update when the signal is emitted. These methods are declared in calc.h as:

QString _displayField;

QString displayField()const;

void setDisplayField(QString displayField);

signals:

void displayFieldChanged();

...and in calc.cpp as:

QString Calc::displayField()const{

return _displayField;

}

void Calc::setDisplayField(QString displayField){

if(_displayField != displayField){

_displayField = displayField;

emit displayFieldChanged();

}

}

The displayFieldChange() signal is not emitted (via the emit keyword) unless the value of the display field has actually changed.

While Q_PROPERTY serves to create a variable that is seen by QML, Q_INVOKABLE marks a method that is callable from QML. In our example, all of the methods that may be executed by button presses are marked in this way in the class definition in calc.h.

Q_INVOKABLE double getTotal()const;

Q_INVOKABLE void setTotal(QString total);

Q_INVOKABLE void clear();

Q_INVOKABLE void clearEntry();

Q_INVOKABLE void backspace();

Q_INVOKABLE void applyOp(QString op);

Q_INVOKABLE void negate();

Q_INVOKABLE void applyDigit(QString digit);

In calc.cpp they are implemented in a corresponding way to their implementation in JavaScript, e.g.:

void Calc::applyOp(QString op){

if(_startNumber){

clear();

setDisplayField(_error);// expecting a number

}else{

_startNumber =true;

if(_previousOp =="=")

setTotal(displayField());

elseif(_previousOp =="+")

add(displayField());

elseif(_previousOp =="-")

subtract(displayField());

elseif(_previousOp =="*")

multiply(displayField());

elseif(_previousOp =="/")

divide(displayField());

setDisplayField(QString("%1").arg(getTotal()));

_previousOp = op;

}

}

To make a Calc object available to QML, it is instantiated and set as a property in main.cpp:

Calc calc;

engine.rootContext()->setContextProperty("calc", &calc);

calc may now be accessed from QML, and its properties and methods referenced directly. Properties appear as variables, as with displayField used as the text contents of the TextEdit element in main.qml:

TextEdit {

id: textEdit

text: calc.displayField

Methods are referenced in a similar manner, but contain a parameter list:

GridButton {

text: "CE"

onClicked: calc.clearEntry()

}

Qt provides additional methods for C++/QML interaction, such as for referencing C++ types and enumerations from QML or for passing more advanced data structures, but the above is sufficient for many applications.

Building on Multiple Platforms

In Qt Creator, clicking on the Build and Run Kit Selector button displays the kits configured for the current project. After selecting the kit to use and the type of build to create (debug, release or profiling), clicking the buttons below the selector will run, run with debugging, or just compile the project, respectively. Most kits do not require additional configuration; but some, such as the Android kit, allow additional properties to be specified if the project is fully set up, such as a keystore that contains a key used to produce a signed release build. The images below depict the kits configured on the author's Windows, Linux and Mac OS X build systems, respectively.

Windows

Linux

Mac OS X

The following images illustrate the result of running the calculator on various platforms. The first is a screenshot of the Windows build machine running the calculator natively on the left, and from within a Linux virtual machine on the right, where the calculator is built for 64-bit Ubuntu. The next two images are photographs of an Android tablet running the calculator in both landscape and portrait orientations (automatically handled without any source code changes). The last image is a screenshot of the Mac OS X build machine, showing the calculator running natively and within the iOS simulator.

Native Windows and Linux

Android

Native Mac OS X and iOS

Each of these platforms is running the identical C++ calculator example without any platform-specific modifications to the code, which is what makes Qt an effective framework for multi-platform development. Of course, although the application runs everywhere, some tweaks may be necessary for proper appearance. For example, while the button sizes and fonts scale based on the window size, the TextEdit field for the display has a fixed pixel size. As the display resolution is different for each platform, the point size that was chosen is not the best choice everywhere, and should be scalable as well. In particular, the display under Android is almost too small to be readable while it is tolerable elsewhere. Keeping in mind issues such as this will lead to fully usable applications across various devices.

Summary

Qt is a handy framework for writing multi-platform applications and may be a way to quickly deploy to multiple architectures. As illustrated above, the same code can build and run without change on multiple systems and devices, thus reducing development time and effort.