Reader small image

You're reading from  Application Development with Qt Creator - Third Edition

Product typeBook
Published inJan 2020
Reading LevelBeginner
Publisher
ISBN-139781789951752
Edition3rd Edition
Languages
Right arrow
Author (1)
Lee Zhi Eng
Lee Zhi Eng
author image
Lee Zhi Eng

Lee Zhi Eng is a self-taught programmer who worked as an artist and programmer at several game studios before becoming a part-time lecturer for 2 years at a university, teaching game development subjects related to Unity and Unreal Engine. He has not only taken part in various projects related to games, interactive apps, and virtual reality but has also participated in multiple projects that are more oriented toward software and system development. When he is not writing code, he enjoys traveling, photography, and exploring new technologies.
Read more about Lee Zhi Eng

Right arrow

Designing Your Application with Qt Designer

Qt is perhaps best known as a cross-platform user interface toolkit, and only in the last few years has Qt Creator really evolved to be a full software development environment. Even in its early releases, however, Qt had an excellent facility for building user interfaces with Qt Designer, now part of Qt Creator. More recently, the developers building Qt have added Qt Quick, as a second option for user interface development. Qt Quick extends the Qt libraries and Qt Designer capabilities of Qt Creator, to build fluid interfaces for touchscreens and set-top boxes (STBs). This is facilitated by the declarative nature of Qt Quick and the Qt Meta-Object Language (QML).

In this chapter, we will cover the following topics:

  • Introducing signals and slots
  • Creating user interfaces with Qt Designer
  • Instantiating forms, message boxes, and dialogs...

Technical requirements

The technical requirements for this chapter include Qt 5.12.3 MinGW 64-bit, Qt Creator 4.9.0, and Windows 10.

Introducing signals and slots

In software systems, there is often the need to couple different objects. Ideally, this coupling should be loose—that is, not dependent on the system's compile-time configuration. This is especially obvious when you consider user interfaces—for example, a button press might adjust the contents of a text widget, or cause something to appear or disappear. Many systems use events for this purpose; components offering data encapsulate that data in an event, and an event loop (or, more recently, an event listener) catches the event and performs some action. This is known as event-driven programming or the event model.

Qt offers the signals and slots mechanism as interfaces to manage events, such as the click event, selection change event, text input event, and so on. When a user does something and an event is triggered, the object (that...

Creating user interfaces with Qt Designer

Let's create a simple calculator application, using Qt Designer and two forms: one form that takes the arguments for an arithmetic operation, and a second dialog form to present the results.

Bear in mind that we will be using these forms in the following sections of this chapter as well. We'll do this twice in this chapter, first to show how to do this using Qt Widgets, and second, by using Qt Quick. The example is contrived but will show you how to create multiple user interface forms in both environments, and will give you practice in working with signals and slots.

F1 is the keystroke you can use in Qt Creator to get help. As you write code in this and subsequent chapters, for any class or method you're curious about, select it and hit F1. You'll be taken to Qt's Help mode, with documentation about that class...

Instantiating forms, message boxes, and dialogs in your application

Qt Designer generates an XML-based layout file (which ends in .ui) for each form you create in Designer. At compile time, Qt Creator compiles the layout into a header file that constructs the components for your user interface layout. The pattern typically used by Qt applications is to construct a private layout class that the main class instantiates. Here's how it works for the main window:

#ifndef MAINWINDOW_H 
#define MAINWINDOW_H 
 
#include <QMainWindow> 
 
namespace Ui { 
  class MainWindow; 
} 
 
class MainWindow : public QMainWindow 
{ 
    Q_OBJECT 
     
public: 
    explicit MainWindow(QWidget *parent = nullptr); 
    ~MainWindow(); 
     
private: 
    Ui::MainWindow *ui; 
}; 
 
#endif // MAINWINDOW_H 

In mainwindow.cpp, we have the following:

#include "mainwindow.h" 
#include...

Wiring the Qt Widgets application logic

The application logic for the calculator is simple: we add a property setter to ResultDialog that lets us set the result field of the dialog, and then we wire up some arithmetic, signals, and slots in MainWindow, to do the actual computation and show the dialog. Let's have a look at the following steps:

  1. First, make the following change to ResultDialog:
void ResultDialog::setResult(float r) 
{ 
    ui->result->setText(QString::number(r)); 
} 

This method takes a float, the value to show in the dialog, and formats the result as a string, using Qt's default formatting. Qt is fully internationalized; if you do this in English-speaking locales, it will use a decimal point, whereas if you do it with a locale set to a region where a comma is used as the decimal separator, it will use a comma instead. The number method is a handy...

Introducing Qt Quick's support for declarative user interface development

Most of the programming you do at the lowest level is imperative: you describe how an algorithm should work (take this value and square it; search for the first occurrence of this string and replace it; format this data this way; and so forth). With Qt Quick, your programming is largely declarative: instead of saying how you say what. For example, in C++ with Qt, we might write code like this to draw a rectangle:

QRect r(0, 0, 16, 16); 
QPainter p; 
p.setBrush(QBrush(Qt::blue)); 
p.drawRect(r); 

This code creates a rectangle of 16 x 16 pixels, allocates a QPainter object that does the drawing, tells the painter that its brush should be colored blue, and then tells the painter to draw the rectangle. In QML, we'd simply write the rectangle code as follows:

import QtQuick 2.12 
Rectangle { 
    width...

Understanding the building of a Qt application

In Chapter 1, Getting Started with Qt Creator, you gained basic familiarity with Qt Designer for Qt Quick applications. Since we have created a calculator program using the C++ language in the previous example, as a comparison, we also create a calculator program in QML so that you can learn the differences.

Let's have another look before we recreate our calculator app in QML. The following screenshot shows the Qt Designer for the Qt Quick window:

Working from the left again, we have the following components:

  1. The view selector, showing that the Qt Designer view is active.
  2. The object hierarchy for the file being edited, showing the parent-child relationship between visible items in that file.
  3. Above the object hierarchy is a palette of the items you can drag out onto the QML editor pane.
  4. Next to the object hierarchy is a summary...

Creating the Qt application

Our calculator has a button for each operation. While we could make each button a separate rectangle and MouseArea, it's far easier to make a single QML button that encapsulates the behavior of a button, including the change in appearance when you press on it, the placement of the button label, and so forth.

Create a new QML file by right-clicking on the project and choosing Add New..., and then, from the Qt items, choose QML File (Qt Quick 2). The button is a Rectangle object that contains a second Rectangle object, a Text label for the button, and a MouseArea object that handles button clicks. Name the file Button.qml, and edit it so that it reads as follows:

import QtQuick 2.12 
 
Rectangle { 
    id: button 
 
    width: 64 
    height: 64 
    property alias operation: buttonText.text 
    signal clicked 
 
    color: "green" 
...

Summary

In the first half of the chapter, we successfully created a Qt application, using the C++ programming language. Then, we also learned how to create the same calculator program, using Qt Quick and the QML scripting language. Throughout these two examples, we have learned the differences between both methods, to allow us to decide which method is best suited for our project.

Qt comes with not one, but two, complementary graphical user interface (GUI) toolkits: Qt Widgets, which takes a traditional widget-based approach to GUI development, and Qt Quick, which provides a declarative approach better suited for platform-agnostic user interfaces for media boxes, some cell phone applications, automobile dashboards, and other embedded environments. For both, Qt offers Qt Designer, a drag-and-drop environment that lets you construct, configure, and preview your user interface as...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Application Development with Qt Creator - Third Edition
Published in: Jan 2020Publisher: ISBN-13: 9781789951752
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Lee Zhi Eng

Lee Zhi Eng is a self-taught programmer who worked as an artist and programmer at several game studios before becoming a part-time lecturer for 2 years at a university, teaching game development subjects related to Unity and Unreal Engine. He has not only taken part in various projects related to games, interactive apps, and virtual reality but has also participated in multiple projects that are more oriented toward software and system development. When he is not writing code, he enjoys traveling, photography, and exploring new technologies.
Read more about Lee Zhi Eng