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

Qt Foundations

Qt is truly one of the best cross-platform frameworks for building applications. As such, it has a large number of core classes to manage data, as well as wrappers around platform services such as threading, the filesystem, network I/O, and of course, graphics.

In this chapter, we discuss some of Qt's core classes that you will find especially handy while writing your applications. In this discussion, we will focus on the bits of Qt that are especially helpful when constructing the business logic for your application. We will begin with a discussion on a handful of useful data classes. After that, we will look at Qt's support for multithreading, a key tool in keeping applications feeling responsive. Next, we will look at accessing files as well as HTTP I/O, an important component in many applications. We will close with a look at Qt's XML parser...

Technical requirements

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

Representing data using Qt's core classes

Probably the most common Qt core class you'll run into is Qt's QString container class for character strings. It has similar capabilities to the C++ STL std::wstring class. As with wstring, it's multibyte. You can construct one from a traditional C-style char * string or another QString.

QString has lots of helper methods, some of which are as follows:

  • append: This appends one QString class onto another.
  • arg: This is used to build up formatted strings (instead of sprintf).
  • at and operator[]: These you can use to access a single character in a QString.
  • operator==, operator!=, operator<, operator>, operator<=, and operator>=: These compare two QStrings.
  • clear: This empties a QString and sets it to the null string.
  • contains: This searches one string for another string or a regular expression.
  • count: This counts...

Multithreading in Qt

A thread is a single line of execution within a single application. Nearly all of today's operating systems are multithreaded; that is, your application can have more than one concurrent line of execution at a time. Multithreading is a key way to improve the responsiveness of an application, because most processors today can execute multiple threads in parallel, and operating systems are optimized to share resources among multiple threads.

Qt supports multithreading over the host operating system through three key classes:

  • QThread
  • QSemaphore
  • QMutex

The first, QThread, represents a single thread of execution, while the latter two are used to synchronize thread access to data structures.

By design, your application runs entirely on the user thread, a single thread of execution that starts when your application starts. You can create new threads of execution...

Accessing files using Qt

Files are basically digital information stored in the form of byte stream that reside somewhere in your hard disk. If your program needs to save or load data, such as for word processing, image editing, media streaming, or program configuration, you will need to access the files stored on your local hard drive. Qt provides us with classes that allow us to easily access the filesystem regardless of the type of operating system.

Qt encapsulates the more generalized notion of byte streams in its QIODevice class, which is the parent class for QFile, as well as network I/O classes such as QTcpSocket. We don't directly create a QIODevice instance, of course, but instead create something such as a QFile subclass and then work with the QFile instance directly to read from and write to the file.

Files and network access usually take time, and thus your applications...

Accessing HTTP resources using Qt

A common thing to do in today's networked world is use the HyperText Transfer Protocol (HTTP) to access a remote resource or service on the web. To do this, your application should first use Qt's support to select a bearer network to make the HTTP request. Then, it should use its support for HTTP to make one or more HTTP requests across the network connection that the bearer network service opened.

To begin with, you need to be sure that you include the network module in your Qt declaration by editing your project's (.pro) file to include the following:

QT += network

Today's computing devices support multiple ways to access the network. For example, an Android tablet can have a built-in 4G wireless wide area network (WAN) adapter as well as a Wi-Fi radio with multiple network configurations for different access points. The...

Parsing XML using Qt

Earlier versions of Qt had a number of XML parsers, each suited to different tasks and different styles of parsing. Each XML parser was used for different formats in older versions of Qt. Fortunately, in Qt 5, this has been streamlined; currently, you only need a single XML parser to parse XML data. The key XML parser to use in the latest Qt version is the QXmlStreamReader class (see https://doc.qt.io/qt-5/qxmlstreamreader.html for details). This class reads from a QIODevice subclass and reads XML tags one at a time, letting you switch on the type of tag the parser encounters. Thus, our parser looks something like this:

QXmlStreamReader xml; 
xml.setDevice(input); 
while (!xml.atEnd())
{ QXmlStreamReader::TokenType type = xml.readNext(); switch(type) { ... // do processing } } if (xml.hasError())
{ ... // do error handling...

Parsing JSON using Qt

JSON is a popular data-transmitting format after XML. It was first standardized in 2013 and has become the most popular format used on the web ever since. JSON data looks something like this:

{
"firstName": "John",
"lastName": "Smith",
"age": 42,
"address": {
"streetAddress": "14 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [{
"type": "home",
"number": "212 686-7890"
},
{
"type": "mobile",
"number": "321 456-7788"
}]
}

As you can see, it is completely different from the XML format. The main reason why it is so popular is because of how human-readable it is and how shorter it is compared...

Summary

We've covered a lot of ground in this chapter, from data structures, to files, to networking. You've learned how you can use fundamental Qt core and networking classes to build the backend logic, which can help you in building the business logic for your application.

Not only that, we've also learned how to make use of multithreading to spread the workload to different CPU threads for speeding up the process. This is especially useful if you're creating an application that does heavy computation and you don't want it to become unresponsive while the computation is still going on. This will severely affect the user experience and ultimately affect your reputation as a brand or company.

Other than that, we've also learned how we can make use of HTTP requests to communicate with a remote server and obtain data from it. Qt makes this process...

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 $15.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