Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

Mastering Qt 5
Mastering Qt 5
Mastering Qt 5
Ebook944 pages9 hours

Mastering Qt 5

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This book will appeal to developers and programmers who would like to build GUI-based applications. Knowledge of C++ is necessary and the basics of Qt would be helpful.
LanguageEnglish
PublisherPackt Publishing
Release dateDec 15, 2016
ISBN9781786464606
Mastering Qt 5

Related to Mastering Qt 5

Related ebooks

Programming For You

View More

Reviews for Mastering Qt 5

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Mastering Qt 5 - Guillaume Lazar

    (missing alt)

    Table of Contents

    Mastering Qt 5

    Credits

    About the Authors

    About the Reviewer

    www.PacktPub.com

    Why subscribe?

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Get Your Qt Feet Wet

    Creating a project

    MainWindow structure

    Qt Designer

    Signals and slots

    Custom QWidget

    Adding a task

    Using a QDialog

    Distributing code responsibility

    Emitting a custom signal using lambdas

    Simplifying with the auto type and a range-based for loop

    Summary

    2. Discovering QMake Secrets

    Designing a cross-platform project

    Adding the Windows implementation

    Adding the Linux implementation

    Adding the Mac OS implementation

    Transforming SysInfo into a singleton

    Exploring Qt Charts

    CpuWidget using QCharts

    Memory using Qcharts

    The .pro file in depth

    Under the hood of qmake

    Beneath Q_OBJECT and signals/slots

    Summary

    3. Dividing Your Project and Ruling Your Code

    Designing a maintainable project

    Defining data classes

    Storing your data in a database

    Protecting your code with a smart pointer

    Implementing the model

    Summary

    4. Conquering the Desktop UI

    Creating a GUI linked to a core shared library

    Listing your albums with AlbumListWidget

    Creating a ThumbnailProxyModel

    Displaying the selected album with AlbumWidget

    Enhancing thumbnails with PictureDelegate

    Displaying a picture with PictureWidget

    Composing your Gallery app

    Summary

    5. Dominating the Mobile UI

    Starting with Qt Quick and QML

    Checking your development environment

    Creating a Qt Quick project

    Preparing your Qt Quick gallery entry point

    Displaying albums with ListView

    Theming the application with a QML singleton

    Loading a database on mobile

    Creating a new album from a custom InputDialog

    Loading images with an ImageProvider

    Displaying thumbnails in a GridView

    Swiping through full resolution pictures

    Summary

    6. Even Qt Deserves a Slice of Raspberry Pi

    Discovering Qt3D

    Configuring Qt for your Raspberry Pi

    Creating an entry point for your Qt3D code

    Setting up the scene

    Assembling your Qt3D entities

    Preparing the board game

    Crafting entities from the factory

    Building a snake engine in JavaScript

    Varying the HUD with QML states

    Profiling your QML application

    Summary

    7. Third-Party Libraries Without a Headache

    Creating your Qt Designer plugin

    Configuring the project for Windows

    Configuring the project for Linux

    Configuring the project for Mac

    Implementing your OpenCV filters

    Designing the UI with FilterWidget

    Exposing your plugin to Qt Designer

    Using your Qt Designer plugin

    Building the image-filter application

    Summary

    8. Animations - Its Alive, Alive!

    Preparing an SDK

    Creating your plugins

    Loading your plugins dynamically

    Using the plugins inside the application

    Discovering the Animation Framework

    Making your thumbnails jump

    Fading the picture in

    Flashing the thumbnail in a sequence

    Summary

    9. Keeping Your Sanity with Multithreading

    Discovering QThread

    Flying over Qt multithreading technologies

    Architecting the Mandelbrot project

    Defining a Job class with QRunnable

    Using QThreadPool in MandelbrotCalculator

    Displaying the fractal with MandelbrotWidget

    Summary

    10. Need IPC? Get Your Minions to Work

    Architecturing an IPC project

    Laying down the foundations with an SDK

    Working with QDataStream and QTcpSocket

    Interacting with sockets in the worker

    Interacting with sockets from the application

    Building your own QTcpServer

    Summary

    11. Having Fun with Serialization

    Architecting the drum machine project

    Creating a drum track

    Making your objects serializable with QVariant

    Serializing objects in JSON format

    Serializing objects in XML format

    Serializing objects in binary format

    Playing low latency sounds with QSoundEffect

    Triggering a QButton with your keyboard

    Bringing PlaybackWorker to life

    Accepting mouse drag and drop events

    Summary

    12. You Shall (Not) Pass with QTest

    Discovering Qt Test

    Executing your tests

    Writing factorized tests with datasets

    Benchmarking your code

    Testing your GUI

    Spying on your application with QSignalSpy

    Summary

    13. All Packed and Ready to Deploy

    Packaging your application

    Packaging for Windows

    Packaging for Linux with a distribution package

    Packaging for Linux with AppImage

    Packaging for Mac OS X

    Packaging for Android

    Packaging for iOS

    Summary

    14. Qt Hat Tips and Tricks

    Managing your workspace with sessions

    Searching with the Locator

    Increasing the compilation speed

    Examining the memory with Qt Creator

    Generating random numbers

    Silencing unused variable warnings

    Logging custom objects to QDebug

    Improving log messages

    Saving your logs to a file

    Generating a command-line interface

    Sending and receiving HTTP data

    Summary

    Mastering Qt 5


    Mastering Qt 5

    Copyright © 2016 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: December 2016

    Production reference: 1121216

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham 

    B3 2PB, UK.

    ISBN 978-1-78646-712-6

    www.packtpub.com

    Credits

    About the Authors

    Guillaume Lazar is a software engineer living near Paris in France. He has worked for different companies, from startups to multinationals, for the last 7 years. He took the opportunity to observe and learn from many team organizations and technologies.

    He eventually founded his own software development company, NeuronalMotion, at the age of 27 with his friend Robin Penea in 2014. Information about it and its open source projects can be found on the comapny's website, www.neuronalmotion.com.

    NeuronalMotion represents to Guillaume a different way of working. The current hierarchical organization that applies to most companies seems obsolete to him. With his own company, he wants to try something different, where each employee will be autonomous.

    Although he defines himself as a Qt framework lover, he likes to mix different technologies and platforms. He also spends time on game development, machine learning, and electronics, because things become alive.

    Creating examples and writing chapters for this book was a serious challenge this year. Some sections were fundamentally changed to match Qt evolution. I would not have been able to achieve this task alone. I wish to thank Robin Penea, my friend and the coauthor of this book. He gave his all to create with me a robust Qt book with modern C++. Our review team, Rohit Kumar Singh, Ray Rischpater, Quentin Canu, Chistophe Dongieux, and Hugo Loi, have done excellent work: they corrected us and raised some important issues. I also want to thank Packt for the good follow up during the writing process. Finally, I thank my family and, particularly, Sophie, my girlfriend, for her support.

    Robin Penea is a software engineer living in France. He has worked for several companies over the last 7 years, on many different technologies (ranging from server application development to embedded programming).

    He founded NeuronalMotion with Guillaume Lazar in 2014 to implement his vision of entrepreneurship and project development. He aims to achieve a self-organized company. More information is available at www.neuronalmotion.com.

    Besides developing with Qt, he likes to tinker with the Android AOSP framework, learn new programming language paradigms, and discover how to interweave technology and real life.

    This book would not have existed without Guillaume Lazar, my friend and the coauthor of the book. He was truly dedicated to designing and crafting the best possible book. I wish to thank our reviewers, Rohit Kumar Singh, Ray Rischpater, Quentin Canu, Christophe Dongieux, and Hugo Loi. Their input was invaluable and definitely raised the quality of the book. Packt played a sensible role, listening to our requests and changes, guiding us through the writing, and monitoring our mental states during this year with benevolence. I also wish to thank my father, Calin, for believing in me. A last word for Flore, my girlfriend, who kept my motivation up and supported me.

    About the Reviewer

    Ray Rischpater is a software engineer and author with over 20 years of industry experience and sixteen books to his credit. Beginning with software development for mobile platforms, he’s done work in several areas, including mobile, web services, building tools for mapping and geospatial engineering, and applying machine learning to geospatial processing problems.

    During this time, he’s participated in the development of Internet technologies and custom applications for Newton, Magic Cap, Palm OS, Java ME, Qualcomm BREW, Apple iOS, and Google Android, as well as several proprietary platforms. Over the last six years, his focus has shifted from mobile applications and services to building tools, software processes, and machine learning models to facilitate mapping the real world. Presently, he’s employed as a software engineering manager at Uber, doing work on mapping and machine learning.

    When not writing for or about software development, he enjoys making music, hiking, and photography with his family and friends in and around the San Lorenzo Valley in central California. When he’s able, he also provides public service through amateur radio as the licensed Amateur Extra station KF6GPE.

    He is the author of Microsoft Mapping with Carmen Au, by Apress (published in 2013) and Application Development with Qt Creator, Second Edition, by Packt (published in 2014). He has written several other books, including Beginning Java ME Platform (Beginning from Novice to Professional), by Apress (published in 2008), Software Development for the QUALCOMM BREW Platform, by Apress (published in 2003), Wireless Web Development, First Edition, by Apress (published in 2002), and Wireless Web Development, Second Edition, by Apress (published in 2004).

    I’d like to thank my wife, Meg Given, for her patience as I worked on yet another book project.

    www.PacktPub.com

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    www.PacktPub.com

    https://www.packtpub.com/mapt

    Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Preface

    C++ is a powerful language. Coupled with Qt, you have in your hands a cross-platform framework that allies performance and ease of use. Qt is a vast framework that provides tools in many areas (GUI, threads, networking, and so on). 25 years after its inception, Qt continues to evolve and grow with each release.

    This book aims to teach you how to squeeze the best out of Qt with the new C++14 additions (lambdas, smart pointers, enum classes, and so on). These two technologies together bring you a safe and powerful development toolbox. Throughout the book, we try to emphasize a clean architecture that lets you create and maintain your application in a complex environment.

    Each chapter is based on an example project that is the basis of all the discussion. Here are some tasters about what we will see in this book:

    Uncover qmake secrets

    Take a deep dive in the model/view  architecture and study how you can build a complex application with this pattern

    Study QML and Qt Quick applications in mobile

    Develop Qt 3D components using QML and JavaScript

    Show how to develop plugins and SDKs using Qt

    Cover the multi-threading technologies provided by Qt

    Build an IPC mechanism using sockets

    Serialize data using XML, JSON, and binary format

    We'll cover all this and much, much more.

    Note that you can take a look at Chapter 14, Qt Hat Tips and Tricks, whenever you want if you want to get some development candies and see some code snippets that might make your development more pleasurable.

    And most importantly, have fun writing Qt applications!

    What this book covers

    Chapter 1, Get Your Qt Feet Wet, lays the fundamentals of Qt and refreshes your memory with a todo application. This chapter covers the Qt project structure, how to use the designer, basic principles of the signals and slots mechanism, and introduces new features of C++14.

    Chapter 2, Discovering QMake Secrets, takes a deep dive in the heart of the Qt compilation system: qmake. This chapter will help you understand how it works, how to use it, and how you can structure a Qt application with platform-specific code by designing a system monitoring application.

    Chapter 3, Dividing Your Project and Ruling Your Code, analyzes the Qt model/view architecture and how a project can be organized by developing a custom library with the core logic of the application. The project example is a persistent gallery application.

    Chapter 4, Conquering the Desktop UI, studies the UI perspective of the model/view architecture with a Qt Widget application relying on the library completed in the previous chapter.

    Chapter 5, Dominating the Mobile UI, adds the missing part of the gallery application with the mobile version (Android and iOS); the chapter covers it with the use of QML, Qt Quick controls, and QML / C++ interactions.

    Chapter 6, Even Qt Deserves a Slice of Raspberry Pi, continues to the road on Qt Quick application with the Qt 3D perspective. This chapter covers how to build a 3D snake game targeted at the Raspberry Pi.

    Chapter 7, Third-Party Libraries Without a Headache, covers how a third-party library can be integrated in a Qt project. OpenCV will be integrated with an image filter application that also provides a custom QDesigner plugin.

    Chapter 8, Animations, It’s Alive, Alive!, extends the image filter application by adding animations and the ability to distribute a custom SDK to let other developers add their own filters.

    Chapter 9, Keeping Your Sanity with Multithreading, investigates the multithreading facilities provided by Qt by building a multithreaded Mandelbrot fractal drawing application.

    Chapter 10, Need IPC? Get Your Minions to Work, broadens the Mandelbrot fractal application by moving the calculation to other processes and managing the communication using sockets.

    Chapter 11, Having Fun with Serialization, covers multiple serialization formats (JSON, XML, and binary) inside a drum machine application in which you can record and load sound loops.

    Chapter 12, You Shall (Not) Pass with QTest, adds tests to the drum machine application and studies how the Qt Test frameworks can be used to make unit tests, benchmarking, and GUI events simulation

    Chapter 13, All Packed and Ready to Deploy, gives insights into how to package an application on all desktop OSes (Windows, Linux, and Mac OS) and mobile platforms (Android and iOS).

    Chapter 14, Qt Hat Tips and Tricks, gathers some tips and tricks to develop with Qt with pleasure. It shows how to manage sessions in Qt Creator, useful Qt Creator keyboard shortcuts, how you can customize the logging, save it to disk, and much more.

    What you need for this book

    All the code in this book can be compiled and run from Qt Creator using Qt 5.7. You can do it from your preferred OS: Windows, Linux, or Mac OS.

    About the mobile-specific chapters, either an Android or an iOS device works, but it is not mandatory (the simulator/emulator can be enough).

    Chapter 6, Even Qt Deserves a Slice of Raspberry Pi, offers to build an application running on a Raspberry Pi. Although it is more fun if we can do it with a real Raspberry Pi, it is not necessary to have one to complete the chapter.

    Who this book is for

    This book will appeal to developers and programmers who would like to build GUI-based application. You should be fluent with C++ and the object-oriented paradigm. Qt knowledge is recommended, but is not necessary.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: The qmake command is executed with the project .pro file.

    A block of code is set as follows:

    void MemoryWidget::updateSeries()

    {

        double memoryUsed = SysInfo::instance().memoryUsed();

        mSeries->append(mPointPositionX++, memoryUsed);

        if (mSeries->count() > CHART_X_RANGE_COUNT) {

            QChart* chart = chartView().chart();

            chart->scroll(chart->plotArea().width()

                          / CHART_X_RANGE_MAX, 0);

            mSeries->remove(0);

        }

    }

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    windows {

        SOURCES += SysInfoWindowsImpl.cpp

        HEADERS += SysInfoWindowsImpl.h

     

       

    debug {         SOURCES += DebugClass.cpp         HEADERS += DebugClass.h     }

     

    }

    Any command-line input or output is written as follows:

    /path/to/qt/installation/5.7/gcc_64/bin/qmake -makefile -o Makefile /path/to/sysinfoproject/ch02-sysinfo.pro

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: In Qt Creator, when you click on the Build button, qmake is invoked.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/masteringqt5. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at [email protected] with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

    Chapter 1.  Get Your Qt Feet Wet

    If you know C++ but have never touched Qt, or if you have made some intermediate Qt applications, this chapter will ensure that your Qt foundations are safe before studying advanced concepts in the following chapters.

    We will teach you to create a simple todo application using Qt Creator. This application will display a list of tasks that you can create/update/delete. We will cover the Qt Creator and Qt Designer interfaces, an introduction to the signal/slot mechanism, the creation of a custom widget with custom signals/slots, and its integration into your application.

    You will implement a todo app using new C++14 semantics: lambdas, auto variables, and for loops. Each one of these concepts will be explained in depth and will be used throughout the book.

    At the end of this chapter, you will be able to create a desktop application with a flexible UI using Qt widgets and new C++ semantics.

    In this chapter, we will cover the following topics:

    Qt project basic structure

    Qt Designer interface

    UI fundamentals

    Signals and slots

    Custom QWidget

    C++14 lambda, auto, for each

    Creating a project

    The first thing to do is to start Qt Creator.

    In Qt Creator, you can create a new Qt project via File | New File or Project | Application | Qt Widgets Application | Choose.

    The wizard will then guide you through four steps:

    Location: You must choose a project name and a location.

    Kits: Target platforms that your project aims at (Desktop, Android, and so on).

    Details: Base class information and name for the generated class.

    Summary: Allows you to configure your new project as a subproject and automatically add it to a version control system.

    Even if all default values can be kept, please at least set a useful project name such as todo or TodoApp. We won't blame you if you want to call it Untitled or Hello world.

    Once done, Qt Creator will generate several files that you can see in the Projects hierarchy view:

    Creating a project

    The .pro file is Qt's configuration project file. As Qt adds specific file formats and C++ keywords, an intermediate build step is performed, parsing all files to generate final files. This process is done by qmake, an executable from the Qt SDK. It will also generate the final Makefiles for your project.

    A basic .pro file generally contains:

    Qt modules used (core, gui, and so on)

    Target name (todo, todo.exe, and so on)

    Project template (app, lib, and so on)

    Sources, headers, and forms

    There are some great features that come with Qt and C++14. This book will showcase them in all its projects. For GCC and CLANG compilers, you must add CONFIG += c++14 to the .pro file to enable C++14 on a Qt project, as shown in the following code:

    QT      += core gui

    CONFIG  += c++14

    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

    TARGET = todo

    TEMPLATE = app

    SOURCES += main.cpp \

              MainWindow.cpp

    HEADERS  += MainWindow.h \

    FORMS    += MainWindow.ui \

    The MainWindow.h and MainWindow.cpp files are the headers/sources for the MainWindow class. These files contain the default GUI generated by the wizard.

    The MainWindow.ui file is your UI design file in XML format. It can be edited more easily with Qt Designer. This tool is a WYSIWYG (What You See Is What You Get) editor that helps you to add and adjust your graphical components (widgets).

    Here is the main.cpp file, with its well-known function:

    #include MainWindow.h

    #include

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

    {

        QApplication a(argc, argv);

        MainWindow w;

        w.show();

        return a.exec();

    }

    As usual, the main.cpp file contains the program entry point. It will, by default, perform two actions:

    Instantiate and show your main window

    Instantiate a QApplication and execute the blocking main event loop

    This is the bottom-left toolbar for Qt Creator:

    Creating a project

    Use it to build and start your todo application in debug mode:

    Check that the project is in Debug build mode.

    Use the hammer button to build your project.

    Start debugging using the green Play button with a little blue bug.

    You will discover a wonderful and beautifully empty window. We will rectify this after explaining how this MainWindow is constructed:

    Creating a project

    An empty MainWindow screenshot

    Tip

    Qt tip

    Press Ctrl B (for Windows/Linux) or Command B (for Mac) to build your project

    Press F5 (for Windows / Linux) or Command +R (for Mac) to run your application in debug mode

    MainWindow structure

    This generated class is a perfect yet simple example of Qt framework usage; we will dissect it together. As mentioned previously, the MainWindow.ui file describes your UI design and MainWindow.h/ MainWindow.cpp is the C++ object where you can manipulate the UI with code.

    It is important to take a look at the header file MainWindow.h. Our MainWindow object inherits from Qt's QMainWindow class:

    #include

    namespace Ui {

    class MainWindow;

    }

    class MainWindow : public QMainWindow

    {

        Q_OBJECT

    public:

        explicit MainWindow(QWidget *parent = 0);

        ~MainWindow();

    private:

        Ui::MainWindow *ui;

    };

    As our class inherits from the QMainWindow class, on top of the header file, we add the corresponding include. The second part is the forward declaration of the Ui::MainWindow, as we only declare a pointer.

    The Q_OBJECT can look a little strange to a non-Qt developer. This macro allows the class to define its own signals/slots and more globally Qt's meta-object system. These features will be covered later in this chapter.

    This class defines a public constructor and destructor. The latter is pretty common. But the constructor takes a parameter parent. This parameter is a QWidget pointer that is null by default.

    A QWidget is a UI component. It can be a label, a textbox, a button, and so on. If you define a parent-child relationship between your window, layout, and other UI widgets, memory management of your application will be easier. Indeed, in this case, deleting the parent is enough because its destructor will take care of also deleting its child, which in turn will delete its children and so on.

    Our MainWindow class extends QMainWindow from the Qt framework. We have a ui member variable in the private fields. The type is a pointer of Ui::MainWindow, which is defined in the ui_MainWindow.h file generated by Qt. It's the C++ transcription of the UI design file MainWindow.ui. The ui member variable will allow you to interact with your UI components (QLabel, QPushButton, and so on) from C++, as shown in the following figure:

    MainWindow structure

    Tip

    C++ tip

    If your class only uses pointers or references for a class type, you can avoid including the header by using forward declaration. That will drastically reduce compilation time.

    Now that the header part is done, we can talk about the MainWindow.cpp source file.

    In the following code snippet, the first include is our class header. The second one is the include required by the generated class Ui::MainWindow. This include is required as we only use a forward declaration in the header:

    #include MainWindow.h

    #include ui_MainWindow.h

    MainWindow::MainWindow(QWidget *parent) :

        QMainWindow(parent),

        ui(new Ui::MainWindow)

    {

        ui->setupUi(this);

    In many cases, Qt generates a good piece of code using the initializer list. The parent argument is used to call the superclass constructor QMainWindow. Our private member variable ui is also initialized now.

    Now that ui is initialized, we must call the setupUi function to initialize all widgets used by the MainWindow.ui design file:

    As we initialize a pointer in the constructor, it must be cleaned in the destructor:

    MainWindow::~MainWindow()

    {

        delete ui;

    }

    Qt Designer

    Qt Designer is a major tool for developing Qt applications. This WYSIWYG editor will help you easily design your GUI. If you switch between Edit mode and Design mode for the MainWindow.ui file, you will see the real XML content and the designer:

    Qt Designer

    The designer displays several parts:

    Form Editor: This is a visual representation of the form (empty for now)

    Widget Box: This contains all widgets that can be used with your form

    Object Inspector: This displays your form as a hierarchical tree

    Property Editor: This enumerates the properties of the selected widget

    Action Editor/Signal & Slots Editor: This handles connections between your objects

    It's time to embellish this empty window! Let's drag and drop a Label widget from the Display Widgets section on the form. You can change the name and the text properties from the properties editor.

    As we are making a todo application, we suggest these properties:

    objectName: statusLabel

    text: Status: 0 todo/0 done

    This label will later display the count of todo tasks and the count of tasks already done. OK, save, build, and start your application. You should now see your new label in the window.

    You can now add a push button with those properties:

    objectName: addTaskButton

    text: Add task

    You should get a result close to this:

    Qt Designer

    Tip

    Qt tip

    You can edit the text property of a widget directly on your form by double-clicking on it!

    Signals and slots

    The Qt framework brings a flexible message exchange mechanism through three concepts: signals, slots, and connections:

    A signal is a message sent by an object

    A slot is a function that will be called when this signal is triggered

    The connect function specifies which signal is linked to which slot

    Qt already provides signals and slots for its classes, which you can use in your application. For example, QPushButton has a signal clicked(), which will be triggered when the user clicks on the button. The QApplication class has a slot quit() function, which can be called when you want to terminate your application.

    Here is why you will love Qt signals and slots:

    A slot remains an ordinary function, so you can call it yourself

    A single signal can be linked to different slots

    A single slot can be called by different linked signals

    A connection can be made between a signal and a slot from different objects, and even between objects living inside different threads!

    Keep in mind that, to be able to connect a signal to a slot, their methods' signatures must match. The count, order, and type of arguments must be identical. Note that signals and slots never return values.

    This is the syntax of a Qt connection:

    connect(sender, &Sender::signalName, 

        receiver, &Receiver::slotName);

    The first test that we can do to use this wonderful mechanism is to connect an existing signal with an existing slot. We will add this connect call to the MainWindow constructor:

    MainWindow::MainWindow(QWidget *parent) :

        QMainWindow(parent),

        ui(new Ui::MainWindow)

    {

        ui->setupUi(this);

        connect(ui->addTaskButton, &QPushButton::clicked,

        QApplication::instance(), &QApplication::quit);

    }

    Let's analyze how a connection is done:

    sender: This is the object that will send the signal. In our example, it is the QPushButton named addTaskButton added from the UI designer.

    &Sender::signalName: This is the pointer to the member signal function. Here, we want do something when the clicked signal is triggered.

    receiver: This is the object that will receive and handle the signal. In our case, it is the QApplication object created in main.cpp.

    &Receiver::slotName: This is a pointer to one of the receiver's member slot functions. In this example, we use the built-in quit() slot from Qapplication, which will exit the application.

    You can now compile and run this short example. You will terminate the application if you click on the addTaskButton of your MainWindow.

    Tip

    Qt tip

    You can connect a signal to another signal. The second signal will be emitted when the first one is triggered.

    Now that you know how to connect a signal to an existing slot, let's see how to declare and implement a custom addTask() slot in our MainWindow class. This slot will be called when the user clicks on ui->addTaskButton.

    This is the updated MainWindow.h:

    class MainWindow : public QMainWindow

    {

        Q_OBJECT

    public:

        explicit MainWindow(QWidget *parent = 0);

        ~MainWindow();

    public slots:

        void addTask();

    private:

        Ui::MainWindow *ui;

    };

    Qt uses a specific slot keyword to identify slots. Since a slot is a function, you can always adjust the visibility (public, protected or private) depending on your needs.

    Add this

    Enjoying the preview?
    Page 1 of 1