Learn Qt 5 - Nicholas Sherriff - E-Book

Learn Qt 5 E-Book

Nicholas Sherriff

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Qt is a mature and powerful framework for delivering sophisticated applications across a multitude of platforms. It has a rich history in the Linux world, is widely used in embedded devices, and has made great strides in the Mobile arena over the past few years. However, in the Microsoft Windows and Apple Mac OS X worlds, the dominance of C#/.NET and Objective-C/Cocoa means that Qt is often overlooked.

This book demonstrates the power and flexibility of the Qt framework for desktop application development and shows how you can write your application once and deploy it to multiple operating systems. Build a complete real-world line of business (LOB) solution from scratch, with distinct C++ library, QML user interface, and QtTest-driven unit-test projects.

This is a suite of essential techniques that cover the core requirements for most LOB applications and will empower you to progress from a blank page to shipped application.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 304

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Learn Qt 5
Build modern, responsive cross-platform desktop applications with Qt, C++, and QML
Nicholas Sherriff
BIRMINGHAM - MUMBAI

Learn Qt 5

Copyright © 2018 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 author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

Commissioning Editor: Kunal ChaudhariAcquisition Editor: Siddharth MandalContent Development Editor: Flavian VazTechnical Editor: Akhil NairCopy Editor: Shaila KusanaleProject Coordinator: Devanshi DoshiProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Jason MonteiroProduction Coordinator: Arvindkumar Gupta

First published: Febraury 2018

Production reference: 1060218

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78847-885-4

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

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.

Contributors

About the author

Nicholas Sherriff (Nick) spent the majority of his career at a major utility company in the UK, working predominantly on the Microsoft Windows platformwith C#,ASP.NET, and SQL Server.Whileleading the native application development functionthere,he experimentedwith C++beforeeventually discoveringQt, utilizing it on a major greenfield project serving several thousandusers.Hecurrentlyworks for acommunications recording software house.At home, Nick enjoys music, video games, and half-hearted calisthenics.

About the reviewer

Marthala Vishnu Vardhan Reddy is an enthusiastic software engineer. He is a Qt software developer and has been working in the automation industry since 2013. He completed his master's in information technology from the University of Stuttgart, Germany. He is currently working on the digitization of metal cutting tool data in the manufacturing industry in the direction of Industry 4.0.

He has done his bachelor's thesis from Institut supérieur d’électronique de Paris, France, where he published an IEEE publication on 5G networks as well.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Hello Qt

Installing Qt

Maintaining your installation

Qt Creator

Scratchpad project

qmake

Summary

Project Structure

Projects, MVC, and unit testing

Project creation

cm-lib

cm-tests

cm-ui

Mastering MVC

QObject

QML

Project output

Summary

User Interface

UX

Creating views

StackView

Anchors

Sizing

Navigation

Fixing conflicts

Summary

Style

Style resource

Font Awesome

Components

Styling the navigation bar

Clicking

Commands

Command bar

Summary

Data

JSON

Object hierarchy

DataDecorators

Entities

Entity collections

Data models

Custom TextBox

Summary

Unit Testing

Unit testing

The default Qt approach

Custom approach

DataDecorator tests

Entity Tests

Mocking

Summary

Persistence

SQLite

Primary keys

Creating clients

Panels

Finding clients

Editing clients

Deleting clients

Summary

Web Requests

Network access

Web Requests

RSS View

RSS

Summary

Wrapping Up

Object factory

UI scaling

Dashboard

Enumerator selectors

Contacts

Deployment preparation

OS X

Linux

Windows

Qt Installer framework

Installation

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Qt is a mature and powerful framework for delivering sophisticated applications across a multitude of platforms. It is widely used in embedded devices, including TVs, satellite set-top boxes, medical equipment, car dashboards, and much more. It also has a rich history in the Linux world, with KDE and Sailfish OS using it extensively and many apps in the stores being developed using Qt. It has also made great strides in the mobile arena over the past few years. However, in the Microsoft Windows and Apple macOS X worlds, the dominance of C#/.NET and Objective-C/Cocoa means that Qt is often overlooked.

This book aims to demonstrate the power and flexibility of the Qt framework and show how you can write your application once and deploy it to multiple operating system desktops. The reader will build a complete real-world Line of Business (LOB) solution from scratch, with distinct library, user interface, and unit test projects.

We will cover building a modern and responsive user interface with QML and wiring it up to rich C++ classes. We will control every aspect of our project configuration and output with QMake, including platform detection and conditional expressions. We will build “self-aware” data entities that can serialize themselves to and from JSON. We will persist those data entities in a database and learn how to find and update them. We will reach out to the internet and consume an RSS feed. Finally, we will produce an installation package so that we can deploy our application onto other machines.

This is a suite of essential techniques that cover the core requirements for most LOB applications and will empower the reader to progress from blank page to shipped application.

Who this book is for

This book targets application developers looking for a powerful and flexible framework for creating modern and responsive applications on Microsoft Windows, Apple Mac OS X, and Linux desktop platforms. Although focused on desktop application development, the techniques discussed are largely applicable to mobile development also.

What this book covers

Chapter 1, Hello Qt, covers how to install and configure the Qt Framework and associated IDE, Qt Creator.

Chapter 2, Project Structure, showcases how to create a new multi-project solution that will be the foundation of our example application.

Chapter 3, User Interface, explores the user interface markup language QML and sketches out our UI's layout.

Chapter 4, Style, explains how to give our UI a modern look and feel with shared resources and reusable components.

Chapter 5, Data, discusses managing the most critical part of any LOB application—the data.

Chapter 6, Unit Testing, gets you started with integrating unit testing into our solution using Qt's testing framework—QtTest.

Chapter 7, Persistence, focuses on persisting our data to disk in a SQLite database.

Chapter 8, Web Requests, assists in using HTTP requests to pull data from a live RSS feed.

Chapter 9, Wrapping Up, dives into packaging and deploying our application.

To get the most out of this book

The reader should be comfortable with C++, but no prior knowledge of Qt or QML is required. On Mac OS X, you will need to install XCode and have launched it at least once. On Windows, you may optionally install Visual Studio in order to have the MSVC compiler available.

Download the example code files

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

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

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 athttps://github.com/PacktPublishing/Learn-Qt-5. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Create theSplashView.qmlfileincm-ui/ui/views".

A block of code is set as follows:

<RCC>

<qresource prefix="/views">

<file alias="MasterView">views/MasterView.qml</file>

</qresource>

<qresource prefix="/">

<file>views/SplashView.qml</file>

<file>views/DashboardView.qml</file>

<file>views/CreateClientView.qml</file>

<file>views/EditClientView.qml</file>

<file>views/FindClientView.qml</file>

</qresource>

</RCC>

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

QT += sql

network

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

$ <Qt Installation Path> \Tools \QtInstallerFramework \3.0\ bin\ binarycreator.exe -c config\config.xml -p packages ClientManagementInstaller.exe

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Replace the Hello World title with Client Management and insert a Textcomponent inside the body of the Window".

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Hello Qt

Qt is a mature and powerful framework for delivering sophisticated applications across a multitude of platforms. It is widely used in embedded devices including TVs, satellite set-top boxes, medical equipment, car dashboards, and much more. It also has a rich history in the Linux world, with KDE and Sailfish OS using it extensively and many apps in the stores being developed using Qt. It has also made great strides in the Mobile arena over the past several years. However, in the Microsoft Windows and Apple Mac OS X worlds, the dominance of C#/.NET and Objective-C/Cocoa mean that Qt is often overlooked.

This book aims to demonstrate the power and flexibility of the Qt framework and show how you can write your application once and deploy it to multiple operating system desktops. We will build a complete real-world line of business (LOB) solution from scratch, with distinct library, user interface, and unit test projects.

We will cover building a modern, responsive user interface with QML and wiring it up to rich C++ classes. We will control every aspect of our project configuration and output with QMake, including platform detection and conditional expressions. We will build “self-aware” data entities that can serialize themselves to and from JSON. We will persist those data entities in a database and learn how to find and update them. We will reach out to the internet and consume an RSS feed. Finally, we will produce an installation package so that we can deploy our application onto other machines.

In this chapter, we will install and configure the Qt framework and associated Integrated Development Environment (IDE) Qt Creator. We will create a simple scratchpad application that we will use throughout the remainder of the book to demonstrate varioustechniques. We will cover the following topics:

Installing Qt

Maintaining your installation

Qt Creator

Scratchpad project

qmake

Installing Qt

Let’s start things off by visiting the Qt website at https://www.qt.io:

The site layout changes fairly frequently, but what you are looking for is to download Qt Open Source for Desktop & Mobile:

From the top-level menu, select

Products

and then

IDE & Tools

Click on

Start for Free

Select

Desktop & Mobile Applications

Click on

Get your open source package

If you continue to use Qt beyond these personal projects, ensure that you read the licensing information available on the Qt website (https://www.qt.io/licensing/). Upgrade to the commercial Qt license if the scope of your projects requires it or if you want access to the official Qt support and the benefits of a close strategic relationship with the Qt company.

The site will detect your operating system and suggest a recommended download:

On Windows, you will be recommended the online installer *.exe file, while on Linux you will be offered a *.run file, and a .dmg file if you are running Mac OS X. In all cases, download and launch the installer:

On Linux, once downloaded, you may need to first navigate to the *.run file and mark it as executable in order to be able to launch it. To do this, right-click on the file in the file manager and click on Properties. Click on the Permissions tab and tick the box that says Allow executing file as program.

After the initial welcome dialog, the first thing you are presented with is the option to sign up for or log in with a Qt account. Feel free to create one if you wish, but for now we’ll go ahead and Skip:

You are then asked to select which components you wish to install.

Your first decision is which version(s) of the Qt framework you want. You can have multiple versions installed side by side. Let's select the latest and greatest (Qt 5.10 at the time of writing) and leave all the older versions unchecked.

Next, expand the selected version and you will see a secondary list of options. All the options where the description reads “Qt 5.9.x Prebuilt Components for ...” are what is known as aKit. AKit is essentially a toolset enabling you to build your application with a specific compiler/linkerand run it on a particular targetarchitecture. Each kit comes with Qt framework binaries compiled specifically for that particular toolsetas well as necessary supporting files.Note that kits do not come with the referenced compiler; you will need to install those ahead of time. One exception to thison WindowsisMinGW(which includes GCC for Windows), which you can optionally install via theToolscomponent list at the bottom.

On Windows, that is exactly what we’ll do, so we select the MinGW 5.3.032 bit kit and also the MinGW 5.3.0 development environment from the Tools section. On my (64-bit) machine, I already have Microsoft Visual Studio 2017 installed, so we will also select the MSVC 2017 64-bit kit to help demonstrate some techniques later in the book. On Linux, we select GCC 64-bit, while on Mac OS, we select macOS 64-bit (which uses the Clang compiler). Note that on Mac OS, you must have XCode installed, and it's a good idea to launch XCode at least once to give it an opportunity to complete its initialization and configuration.

Feel free to press pause, go and install whatever other IDEs or compilers you want to use, and then come back and pick the kits to match. It doesn’t matter too much which you go for—the techniques explained throughout the book are applicable regardless of the kit, you may just get slightly different results. Note that the available kits you are presented with will differ depending on your operating system and chipset; for example, if you are on a 32 bit machine, you won’t be offered any 64 bit kits.

Below the kits are some optional Qt APIs (such as Qt Charts), which we won’t need for the topics covered in this book, but feel free to add them in if you want to explore their functionality. Note that they may have different licensing agreements from the core Qt framework.

Regardless of kits and APIs, you will note in the Tools section that Qt Creator is installed by default and that is the IDE we will be using throughout this book:

Once you are finished making your selections, click on NextandUpdateto kick off the installation.

It's generally a good idea to leave the installation location as the default for consistency across machines, but feel free to install it wherever you want.

Maintaining your installation

Once installed, you can update, add, and remove components (or even the entire Qt installation) via the Maintenance Toolapplication that is located in the directory you installed Qt to.

Launching this tool provides pretty much the same experience as when we first installed Qt. The Add or remove components option is the one you want to add in items you may have previously not needed, including kits and even entirely new releases of the framework. Unless you actively uncheck them, components already installed on your system will not be affected.

Qt Creator

While a detailed overview of Qt Creator is beyond the scope of this book (the Qt Creator manual is accessible via the Help mode as described here), it’s worth having a quick whistle stop tour before we get stuck to our first project, so launch the freshly installed application and we’ll take a look:

At the upper left-hand side (1) are the different areas or modes of the application:

Welcome

mode is the default when Qt Creator is launched and is the jumping off point to create or open projects. There is an extensive set of examples that help showcase the various capabilities of the framework as well as a selection of tutorial videos.

Edit

mode is where you will be spending the vast majority of your time and is used for editing all the various text-based files.

Design

is accessible only when you have a UI file open and is a WYSIWYG editor for views. Although useful for UX design and basic layout work, it can get frustrating quite quickly and we will do all of our QML work in Edit mode instead. Working this way promotes understanding of the QML (as you have to write it) and also has the advantage that the editor is not adding code that you don’t want.

Debug

mode is used for debugging applications and is beyond the scope of this book.

Projects

mode is where configuration for the project is managed, including the build settings. Changes made here will be reflected in the

*.pro.user

file.

Help

mode takes you to the Qt Creator manual and Qt library reference.

Pressing F1 while the cursor is on a recognized Qt symbol will automatically open context sensitive help for that symbol.

Below that, we have the build/run tools (2):

Kit/Build

lets you select your kit and set the build mode

Run

builds and runs the application without debugging

Start Debugging

builds and runs the application with a debugger (note that you must have a debugger installed and configured in your selected kit for this to work)

Build Project

builds the application without running it

Along the bottom (3), we have a search box and then several output windows:

Issuesdisplays any warnings or errors. For compiler errors relating to your code, double-clicking on the item will navigate you to the relevant source code.

Search Results

lets you find occurrences of text within various scopes.

Ctrl

+

F

brings up a quick search, and from there selecting

Advanced…

also brings up the Search Results console.

Application Output

is the console window; all output from application code like

std::

cout and Qt’s equivalent

qDebug()

appears here, along with certain messages from the Qt framework.

Compile Output

contains output from the build process, from qmake through to compilation and linking.

Debugger Console

contains debugging information that we won’t be covering in this book.

General Messages

contains other miscellaneous output, the most useful of which is from qmake parsing of

*.pro

files, which we will look at later.

The search box really is a hidden gem and saves you from clicking through endless files and folders trying to find what you are looking for. You can start typing the name of a file you are looking for in the box and a filtered list appears with all matching files. Simply click on the file you want, and it opens in the editor. Not only that, there are a large number of filters you can apply too. Click your cursor in the empty search box and it displays a list of available filters. The filter m, for example, searches for C++ methods. So, say you remember writing a method called SomeAmazingFunction() but can't remember where it is, just head over to the search box, start typing m Some, and it will appear in the filtered list.

In Edit mode, the layout changes slightly and some new panes appear. Initially, they will be empty, but once you have a project open, they will resemble the following:

Next to the navigation bar is the project explorer, which you can use to navigate the files and folders of your solution. The lower pane is a list of all of the documents you currently have open. The larger area to the right is the editor pane where you write your code and edit documents.

Double-clicking on a file in the project explorer will generally open it in the editor pane and add it to the open documents list. Clicking on a document in the open documents list will activate it in the editor pane, while clicking on the small x to the right of the filename closes it.

Panes can be changed to display different information, resized, split, closed, and possibly filtered or synchronized with the editor using the buttons in the headers. Experiment to get a feel for what they can do.

As you would expect with a modern IDE, the look and feel of the chrome and the text editor is very customizable. Select Tools > Options… to see what is available. I generally edit the following:

Environment > Interface > Theme > Flat

Text Editor > Fonts & Colors > Color Scheme > My own scheme

Text Editor > Completion > Surround text selection with brackets > Off

Text Editor > Completion > Surround text selection with quotes > Off

C++ > Code Style > Current Settings > Copy…

then

Edit…

Edit Code Style > Pointers and References > Bind to Type name > On (other options Off)

Play around and get things how you like them.

Scratchpad project

To demonstrate how minimal a Qt project can be and to give us a programming sandpit to play around in, we’ll create a simple scratchpad project. For this project, we won’t even use the IDE to do it for us, so you can really see how projects are built up.

First, we need to create a root folder to store all of our Qt projects. On Windows, I use c:\projects\qt, while I use ~/projects/qt on Linux and Mac OS. Create this folder wherever works for you.

Note that file syncing tools (OneDrive, DropBox, and so on) can sometimes cause problems with project folders, so keep your project files in a regular unsynchronized folder and use version control with a remote repository for backups and sharing.

For the remainder of the book, I will loosely refer to this folder as <Qt Projects> or similar. We will also tend toward using the Unix style / separator for file paths, rather than Windows style back slash \. So, for readers using Windows, <Qt Projects>/scratchpad/amazing/code is equivalent to c:\projects\qt\scratchpad\amazing\code. Qt tends to favor this convention too.

Equally, the majority of screenshots in the remainder of the book will be from Windows, so Linux/Mac users should interpret any references to c:\projects\qt as ~/projects/qt.

In our Qt projects folder, create a new folder scratchpad and navigate into it. Create a new plain text file called scratchpad.pro, remembering to remove any .txt extension the operating system may want to add for you.

Next, simply double-click on the file and it will open in Qt Creator:

Here, Qt Creator is asking us how we want our project to be configured, namely, which kits we want to use when building and running our code. Pick one or more available kits and click on Configure Project. You can easily add and remove kits later, so don’t worry about which ones you select.

If you switch back to the filesystem, you will see that Qt Creator has created a new file for us called scratchpad.pro.user. This is just an XML file containing configuration information. If you delete this file and open the .pro file again, you will be prompted to configure the project again. As its name suggests, the configuration settings are relevant to the local user, so often if you load a project created by someone else, you will need to go through the configure project step then too.

With the project successfully configured, you will see the project has been opened, even with a completely empty .pro file. That's about as minimal as a project can get!

Back in the filesystem, create the following plain text files:

main.cpp

main.qml

qml.qrc

I will go through each of these files, explain their purpose, and add their content soon. In a real-world project, we would of course use the IDE to create the files for us. Indeed, that’s exactly what we’ll do when we create our main solution files. However, the purpose of doing it this way is to show you that when you boil it down, a project is just a bunch of text files. Never be afraid to create and edit files manually. A lot of modern IDEs can confuse and overcomplicate with menu after menu and never-ending option windows. Qt Creator may miss some of the advanced bells and whistles of other IDEs but is refreshingly lean and straightforward.

With those files created, double-click on the scratchpad.pro file in the Projects pane and we’ll start editing our new project.