Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Getting Started with Qt 5
Getting Started with Qt 5

Getting Started with Qt 5: Introduction to programming Qt 5 for cross-platform application development

eBook
$15.99 $22.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Getting Started with Qt 5

Introducing Qt 5

Qt gives developers a great toolbox with which to create fantastic and practical applications with minimal stress, as you will soon discover. In this chapter, we will introduce Qt and describe how to set it up on a machine. By the end of the chapter, you should be able to do the following:

  • Install Qt
  • Write a simple program in Qt
  • Compile and run a Qt program

The objectives have been kept simple and straightforward. So let's get started!

Installing Qt on Linux

The Ubuntu operating system makes it reasonably easy to install Qt 5. Issue the following commands to set up your box:

sudo apt-get install qt5-default

After the installation, Qt programs will be compiled and run from the command line. In Chapter 6, Connecting Qt with Databases, we will illustrate how to connect to the database using Qt. Issue the following command to ensure that the relevant libraries are installed for Qt to work with. The database that will'll connect to is MySQL:

sudo apt-get install libqt5sql5-mysql

Installing Qt on macOS

There are a variety of ways to get Qt installed on a Mac. To begin the process of installing Qt 5 on your Mac, you need to get Xcode installed on your machine. Issue the following commands on the Terminal:

xcode-select --install

If you get the following output, then you are ready for the next series of steps:

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

HomeBrew is a package management software tool that allows you to easily install Unix tools that don't come shipped with the macOS.

If you don't already have it on your machine, you can install it by issuing the following command in a Terminal:

 /user/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

After that, you should issue yet another set of commands to get Qt installed via the Terminal:

curl -O https://raw.githubusercontent.com/Homebrew/homebrew-core/fdfc724dd532345f5c6cdf47dc43e99654e6a5fd/Formula/qt5.rb

brew install ./qt5.rb

In a few chapters' time, we will be working with the MySql database. To configure Qt 5 with MySql, issue the following command:

brew install ./qt5 --with-mysql

This command should take a while to complete and, assuming nothing goes wrong, you are ready to write Qt programs.

Installation on Windows

For readers using Windows, installation remains simple, albeit a little less straightforward. We can start by heading over to http://download.qt.io.

Select official_releases/, then online_installers/, and opt to download qt-unified-windows-x86-online.exe.

Run the program and opt to create an account. Click through to select the installation folder and don't forget to select the MinGW 5.3.0 32 bit option as the compiler when selecting the components that need to be installed.

Most of the commands in this book should run in this IDE.

What is Qt?

Now that we have set up our boxes to start development, let's put together a hello world example. First, however, let's take a brief detour.

Qt is a toolkit for creating Graphical User Interfaces (GUI), as well as cross-platform applications. GUI applications are programs that employ the use of the mouse to issue commands to the computer for execution. Though Qt can, in some cases, be used without necessarily making use of this, therein lies its utility.

The difficulty in trying to produce the same look, feel, and functionality across multiple operating systems is one big hurdle you have to deal with when writing GUI applications. Qt completely does away with this impediment by providing a means to write code only once and ensuring that it runs on most operating systems without requiring much or any change.

Qt makes use of some modules. These modules group related functionalities together. The following lists some modules and what they do:

  • QtCore: As the name implies, these modules contains core and important classes for the Qt framework. These include containers, events, and thread management, among others.
  • QtWidgets and QtGui: This module contains classes for calling widgets. Widgets are the components that make up the majority of a graphical interface. These include buttons, textboxes, and labels.
  • QtWebkit: This module makes it possible to use web pages and apps within a Qt application.
  • QtNetwork: This module provides classes to connect to and communicate with network resources.
  • QtXML: For parsing XML documents, this module contains useful classes.
  • QtSQL: This module is feature-rich with classes and drivers that allow for connecting to databases, including My SQL, PostgreSQL, and SQLite.

Hello world in Qt

In this section, we will put together a very simple hello world program. The program will show a simple button within a window. Create a file called hello.cpp in a newly created folder called hello_world. Open the file and insert the code:

#include <QApplication>
#include <QLabel>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLabel label("Hello world !");
label.show();
return app.exec();
}

This looks like a regular C++ program, with the exception of unfamiliar classes being used.

Like any regular program, the int main() function is the entry point of our application.

An instance of the QApplication class is created, called app, and the arguments passed to the main() function. The app object is required because it sets off the Event loop that continues to run until we close the application. Without the QApplication object, you cannot really create a Qt GUI application.

However, it is possible to use certain aspects of Qt without the need to create an instance of QApplication.

Also, the constructor for QApplication requires that we pass the argc and argv to it.

We instantiate an object of the QLabel class, label. We pass the "Hello World!" string to its constructor. A QLabel represents what we call a widget, which is a term used to describe visual elements on the screen. Labels are used to hold text for display.

By default, created widgets are hidden. To display them, a call to the show() function has to be made.

To start the Event loop, the app.exec() line is executed. This passes control of the application to Qt.

The return keyword will pass an integer back to the operating system, indicating the state of the application when it was closed or exited.

To compile and run our program, navigate to the folder where hello.cpp is stored. Type the following command in the Terminal:

% qmake -project

This will create the hello_world.pro file. The name hello_world is the name of the folder where hello.cpp is located. The generated file should change, depending on the location you stored the hello.cpp file.

Open the hello_world.pro file with any text editor of your choice. The following lines deserve some explanation:

TEMPLATE = app

The value, app, here means that the final output of the project will be an application. Alternatively, it could be a library or sub-directory:

TARGET = hello_world

The name, hello_world, here is the name of the application or (library) that will be executed:

SOURCES += hello.cpp

Since hello.cpp is the only source file in our project, it is added to the SOURCES variable.

We need to generate a Makefile that will detail the steps needed to compile our hello world program. The benefit of this autogenerated Makefile is that it takes away the need for us to know the various nuances involved in compiling the program on the different operating systems.

While in the same project directory, issue the following command:

% qmake

This generates a Makefile in the directory.

Now, issue the following command to compile the program:

% make

The following error will be produced (along with further information) as the output from running the make command:

#include <QApplication>
^~~~~~~~~~~~

Earlier on, we mentioned that various components and classes are packaged into modules. The QApplication is being utilized in our application, but the correct module has not been included. During compilation, this omission results in an error.

To fix this issue, open the hello_world.pro file and insert the following lines after the line:

INCLUDEPATH += .
QT += widgets

This will add the QtWidget module, along with the QtCore modules, to the compiled program. With the correct module added, run the make command again on the command line:

% make

A hello_world file will be generated in the same folder. Run this file from the command line as follows:

% ./hello_world

On a macOS, the full path to the executable will be specified with the following path from the command line:

./hello_world.app/Contents/MacOS/hello_world

This should produce the following output:

Well, there is our first GUI program. It displays the Hello world ! in a label. To close the application, click on the Close button of the window.

Let's add a dash of Qt Style Sheet (QSS) to give our label a little effect!

Modify the hello.cpp file as follows:

#include <QApplication>
#include <QLabel>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLabel label("Hello world !");
label.setStyleSheet("QLabel:hover { color: rgb(60, 179, 113)}");
label.show();
return app.exec();
}

The only change here is label.setStyleSheet("QLabel:hover { color: rgb(60, 179, 113)}");.

A QSS rule is passed as an argument to the setStyleSheet method on the label object. The rule sets every label within our application to show the color green when the cursor hovers over it.

Run the following commands to recompile the application and run it:

% make
% ./hello_world

The program should appear as in the following screenshot. The label turns green when the mouse is placed over it:

Summary

This chapter laid the foundation for getting to know Qt and what it can be used for. Installing of Qt on macOS and Linux was outlined. A small hello world application was written and compiled, all from the command line, without any need for an IDE. This meant that we were also introduced to the various steps that lead to the final program.

Finally, the hello world application was modified to employ QSS in a bid to show what other things can be done to a widget.

In Chapter 2, Creating Widgets and Layouts, we will explore more widgets in Qt and how to organize and group them.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how to write, assemble, and build Qt application from the command line
  • Understand key concepts like Signals and Slots in Qt
  • Best practices and effective techniques for designing graphical user interfaces using Qt 5

Description

Qt is a cross-platform application framework and widget toolkit that is used to create GUI applications that can run on different hardware and operating systems. The main aim of this book is to introduce Qt to the reader. Through the use of simple examples, we will walk you through building blocks without focusing too much on theory. Qt is a popular tool that can be used for building a variety of applications, such as web browsers, media players such as VLC, and Adobe Photoshop. Following Qt installation and setup, the book dives straight into helping you create your first application. You will be introduced to Widgets, Qt's interface building block, and the many varieties that are available for creating GUIs. Next, Qt's core concept of signals and slots are well illustrated with sufficient examples. The book further teaches you how to create custom widgets, signals and slots, and how to communicate useful information via dialog boxes. To cap everything off, you will be taken through writing applications that can connect to databases in order to persist data. By the end of the book, you should be well equipped to start creating your own Qt applications and confident enough to pick up more advanced Qt techniques and materials to hone your skills.

Who is this book for?

Anyone trying to start development of graphical user interface application will find this book useful. One does not need prior exposure to other toolkits to understand this book. In order to learn from this book you should have basic knowledge of C++ and a good grasp of Object Oriented Programming. Familiarity with GNU/Linux will be very useful though it's not a mandatory skill.

What you will learn

  • Set up and configure your machine to begin developing Qt applications
  • Discover different widgets and layouts for constructing UIs
  • Understand the key concept of signals and slots
  • Understand how signals and slots help animate a GUI
  • Explore how to create customized widgets along with signals and slots
  • Understand how to subclass and create a custom windows application
  • Understand how to write applications that can talk to databases.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 28, 2019
Length: 136 pages
Edition : 1st
Language : English
ISBN-13 : 9781789955125
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Feb 28, 2019
Length: 136 pages
Edition : 1st
Language : English
ISBN-13 : 9781789955125
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 130.97
Mastering Qt  5
$48.99
Getting Started with Qt 5
$32.99
Hands-On High Performance Programming with Qt 5
$48.99
Total $ 130.97 Stars icon

Table of Contents

7 Chapters
Introducing Qt 5 Chevron down icon Chevron up icon
Creating Widgets and Layouts Chevron down icon Chevron up icon
Working with Signals and Slots Chevron down icon Chevron up icon
Implementing Windows and Dialog Chevron down icon Chevron up icon
Managing Events, Custom Signals, and Slots Chevron down icon Chevron up icon
Connecting Qt with Databases Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.1
(7 Ratings)
5 star 28.6%
4 star 28.6%
3 star 0%
2 star 14.3%
1 star 28.6%
Filter icon Filter
Top Reviews

Filter reviews by




George McGinn Jul 03, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I new nothing about Qt5 before I got this book. After working the 6 chapters in it, I am designing my own GUI and even creating, updating and using MySQL databases in C++.This book is a great introduction and you will come away with a basic understanding of Qt5. If you want to advance to more features and a better understanding, you can supplement this book with one that goes into greater detail, like the Qt5 Cookbook or the Mastering Qt5 book.If you are not versed in C++, then this book will not help you with the C++ code. You need to be at least an intermediate level (understand the "this" pointer and other object-oriented principles) to carry the knowledge gained forward.
Amazon Verified review Amazon
Ian Mars P. Acut Feb 04, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Nice to have Qt 5 book on my shelf!
Amazon Verified review Amazon
Brendan Chong Aug 15, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Description was a little deceiving, doesn't really show you how to develop cross platform. But still worth the purchase
Amazon Verified review Amazon
Cliente Amazon Aug 20, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Il libro costituisce un buon mezzo per entrare nel mondo delle qt5 per chi ne fosse del tutto digiuno. Tutti gli esempi sono corredati del codice da scaricare da github. Il codice viene spiegato in dettaglio nel libro. Tutti gli esempi sono funzionanti senza dover operare correzioni. In definitiva un buon testo per novizi, dove trovare i principi di base delle qt5. Necessaria una conoscenza, anche minima, di C e C++.
Amazon Verified review Amazon
Retired Developer Sep 24, 2022
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Book gives a good overview of QT 5.Oriented to Linux or MacOS user.Have been unable to get the examples in the book to run in a Windows environment.If there were a book out there focused on QT 5 in a Windows environment, I'd return this book.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.