83,99 €
Learn the complete Qt ecosystem and its tools and build UIs for mobile and desktop applications
Qt 5.9 is an application development framework that provides a great user experience and develops full-capability applications with Qt Widgets, QML, and even Qt 3D. This learning path demonstrates the power and flexibility of the Qt framework for desktop application development and shows how you can write an application once and deploy it to multiple operating systems. It will address all the challenges while developing cross-platform applications with the Qt framework.
This course will give you a better understanding of the Qt framework and tools to resolve serious issues such as linking, debugging, and multithreading. It will also upskill you by explaining how to create a to-do-style app and taking you through all the stages in building a successful project. You will build a suite of apps; while developing these apps, you’ll deepen your knowledge of Qt Quick's layout systems, and see Qt 3D and widgets in action. The next project will be in the industrial and agricultural sectors: making sense of sensor data via a monitoring system. Your apps should run seamlessly across devices and operating systems such as Android, iOS, Windows, or Mac, and be cost-effective by integrating with existing web technologies. You take the role of lead developer and prototype a monitoring system. In doing so, you’ll get to know Qt's Bluetooth and HTTP APIs, as well as the Charts and Web Engine UI modules. These projects will help you gain a holistic view of the Qt framework.
This book will appeal to developers and programmers who would like to build GUI-based applications. Knowledge of C++ is necessary and a basic familiarity with Qt would be helpful.
Nicholas Sherriff (Nick) spent the majority of his career at a major utility company in the UK, working predominantly on the Microsoft Windows platform with C#, ASP.NET, and SQL Server. While leading the native application development function there, he experimented with C++ before eventually discovering Qt, utilizing it on a major green-field project serving several thousand users. He currently works for a communications recording software house. At home, Nick enjoys music, video games, and half-hearted calisthenics. 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 company's website: NeuronalMotion. 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." 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: NeuronalMotion. Besides developing with Qt, he likes to tinker with the Android AOSP framework, learn new programming language paradigms, and discover how to interweave technology with real life. Marco Piccolino is a consultant, technical trainer and speaker developing Qt apps for businesses and consumers on a daily basis. He is the founder of the QtMob Slack chat, a community of Qt application developers with a focus on mobile, resource sharing and problem solving. Marco's main professional interests include application architecture, test-driven development, speech and language technologies, and everything Qt.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1152
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this learning path 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 learning path to ensure the accuracy of the information presented. However, the information contained in this learning path is sold without warranty, either express or implied. Neither the author(s), 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 learning path.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this learning path by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Authors:Nicholas Sherriff, Guillaume Lazar, Robin Penea, Marco PiccolinoReviewer: Vishnu Reddy, Sivan Greenberg, Ray Rischpater, Pierre-Yves Siret, Jürgen Bocklage-Ryannel Content Development Editor: Priyanka SawantGraphics: Jason MonterioProduction Coordinator: Nilesh Mohite
Published on: September 2018
Production reference: 1240918
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78953-190-9
www.packtpub.com
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.
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
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.
Title Page - Courses
Copyright and Credits - Courses
End to End GUI Development with Qt5
Packt Upsell - Courses
Why subscribe?
PacktPub.com
Preface
Who this learning path is for
What this learning path covers
To get the most out of this learning path
Download the example code files
Conventions used
Get in touch
Reviews
Learn Qt 5
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
Mastering Qt 5
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
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
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
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
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
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
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
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
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
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
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
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
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
Qt 5 Projects
Writing Acceptance Tests and Building a Visual Prototype
Don't come to me with an idea, come to me with a plan
The problem — what's in my fridge?
The solution — an app idea
The plan — start from user stories
Writing features and scenarios
Implementing scenarios as acceptance tests
Our project structure
QML and C++ — when to use each of them
Writing the first acceptance tests in C++
Creating the first C++ test case
Adding the first C++ test
Given there is a list of available grocery items
And (given) one or more grocery items are actually available
When I check available groceries
Then I am given the list of available grocery items
And (then) the grocery items are ordered by name, ascending
A huge step for humanity
Writing usecase tests in QML
A short QML primer
Expressing the first acceptance test in QML
Building a visual prototype
Deciding upon the UI technology
What kind of visual metaphors should our application use?
What kind of devices should our application run on?
Should a non-coding designer implement the UI?
Why limit yourself to one?
Our initial choice
Prototyping with Qt Quick Designer
Creating the UI subproject
Laying out the UI components required by the scenarios
Check available groceries
Add grocery item
Remove grocery item
Taking it further
Summary
Defining a Solid and Testable App Core
Implementing the first usecase
Creating the usecase class
Anatomy of a QObject-derived class
Describing the usecase flow with signals and slots
From usecases to business objects
Introducing the almighty QVariant
Implementing the GroceryItems entity
Implementing a fake data repository
Making the first usecase test pass
Using the AutoTest plugin
Wait a second!
Adding a textual user interface
Setting up the console application project
Writing the textual application
QCoreApplication's many responsibilities
Creating the business objects
Defining application output upon success
Collecting and acting upon user input
Running the console app
About unit testing
Summary
Wiring User Interaction and Delivering the Final App
Completing the app's core functionality
Adding a grocery item
Defining the precondition step
Test init and cleanup
Defining the usecase action step
Defining the first outcome step
Defining the second outcome step
use case implementation
Implementing the GroceryItems entity
Removing a grocery item
Adding a fridge
Connecting visual input/output and usecases
Setting up the client application
Exposing C++ objects to QML
QML engines and contexts
Exposing object instances via context properties
Triggering usecases from the UI
Triggering usecases::CheckAvailabeGroceries::run
Triggering usecases::AddGroceryItem::run
Triggering usecases::RemoveGroceryItem::run
Showing usecase outcomes in the UI
Exposing the groceryItems list to QML
Binding groceriesListView.model to groceryItems.list
Trying out the usecases from the UI
Improving the UI
Deploying the app
Deploying the app to macOS
Deploying the app to Windows
Deploying the app to Android
Deploying the app to iOS
Deploying the app to Linux
Summary
Learning About Laying Out Components by Making a Page Layout Tool
A tool to prototype page layouts quickly
Initial setup
Creating sub-projects
Previewing QML code
Creating a QML module
Creating a Qt Resource Collection
Back to scenarios
Adding a panel to the page
Implementing usecases and entities
Designing and implementing the UI for the usecase
The anchors positioning model
Adding the page
Creating the comic panels
The Qt Quick Layouts system
Managing comic panels with a grid layout
Creating new panels dynamically with a repeater
Defining the comic panel
Simulating the usecase action
Removing a panel from the page
Taking a picture and loading it into a panel
Loading an existing picture into a panel
Summary
Creating a Scene Composer to Explore 3D Capabilities
Arranging 3D elements in a composition
Defining feature scenarios
Adding elements to a composition
Removing elements from a composition
Saving a composition as an image
Defining entities and their visual counterparts
Introducing Qt 3D
Comparing C++ and QML APIs
Previewing Qt 3D entities in QML
The Element entity
Adding visual components to the element
Varying the properties of the mesh
Changing the element's position
Selecting an element
Dealing with user input
Keeping track of the currently selected element
The Composition entity
Having the composition reference a list of entities
Previewing the composition
Adding elements to the composition
Adding camera and interaction to the composition
Adding custom lighting and changing the background color
Creating the client application
Exporting QML components in a namespaced module
Setting up the client application
Creating the 2D controls
Adding the controls menu and the element creation options
Adding the Background color selector and the grab image button
Prototyping the usecases in JavaScript
Adding the elements business object
Adding the usecases
Implementing add element to Composition
Implementing remove element from composition
Implementing save composition to an image
Going further
Summary
Building an Entity-Aware Text Editor for Writing Dialogue
Writing comic scripts efficiently
Defining use cases
Setting up the project
Prototyping the UI
Introducing Qt Widgets
Using Qt Widgets Designer
Adding the main layout
Adding the left column and the text editor
Adding the List View, button, and line edit
Implementing the characters entity
Introducing QAbstractItemModel and QAbstractListModel
Creating the characters entity
Adding a character to the characters model
Inserting a character's name into the dialogue script
Auto-highlighting a character name
Saving the comic script
Exporting the comic script to PDF
Styling the UI
Summary
Sending Sensor Readings to a Device with a Non-UI App
Outline
Setting up the project
Publishing sensor readings
Setting up the use case project
Implementing the background steps
Defining the sensor entity
Introducing Qt Sensors
Modeling the sensor abstraction
Implementing the Broadcaster entity
Adding the broadcaster Bluetooth channel
Setting up the channel project
Defining the BroadcasterChannel API
Introducing the Qt Bluetooth module
Creating the channel base and derived classes
Implementing the channel initialization method
Making the server listen to the adapter
Providing information about the service ID
Providing information about the service's textual descriptors
Providing information about service discoverability
Providing information about the transport protocol
Registering the service with the adapter
Connecting the broadcaster channel to the Broadcaster entity
Gluing components into the CM Broadcast console app
Including and instantiating the components
Testing the service discovery
Summary
Building a Mobile Dashboard to Display Real-Time Sensor Data
Overview
Project setup
Setting up the CM Monitor project
Creating the Bluetooth Receiver channel project
Implementing the Bluetooth Receiver channel
Implementing the init method
Implementing the receiveReadings method
Having the broadcaster emit readings at regular intervals
Checking the broadcaster-receiver communication
Implementing the readings chart
Introducing QtCharts
Adding a line series to the chart view
Wiring the receiverChannel to the chart
Adding internationalization support
Marking strings for translation
Generating the XML translation files
Translating a string
Compiling translations
Loading translations
Summary
Running a Web Service and an HTML5 Dashboard
Overview
Creating a BroadcasterChannel based on HTTP
Networking support in Qt
Compiling and linking the QHttp library
Adding the QHttp library to the channel broadcaster project
Implementing the HTTP BroadcasterChannel
Making an HTTP ReceiverChannel implementation
Subclassing the ReceiverChannel
Implementing the constructor and init method
Performing the HTTP request and consuming the response
Implementing an HTML5 UI
Browser technologies in Qt: WebEngine, WebView, and WebKit
Adding WebEngineView to cmmonitor
Data transport between app and browser with WebChannel
Adding an HTML5 time series
Summary
Additional and Upcoming Qt Features
Additional Qt features in 5.9 LTS
New and upcoming Qt features
Bibliography
Qt 5.9 is an application development framework that provides a great user experience and develops full-capability applications with Qt Widgets, QML, and even Qt 3D. This learning path 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. It will address all the challenges while developing cross-platform applications with the Qt framework.
Through this learning path, you will have a better understanding of the Qt framework and the tools to resolve serious issues such as linking, debugging, and multithreading. It will also upskill you by teaching how to create a to-do style app by going via all stages for building a successful project. You will build a suite of apps and while developing these apps you’ll deepen your knowledge of Qt Quick's layout systems, and see Qt 3D and Widgets in action. The next project will be for industrial and agricultural sectors, to make sense of sensor data via a monitoring system. The apps should run seamlessly across devices and operating systems like Android, iOS, Windows, or Mac, and be cost-effective by integrating with existing web technologies. You take the role of lead developer and prototype the monitoring system. In doing so you’ll get to know Qt's Bluetooth and HTTP APIs, as well as the Charts and Web Engine UI modules. These projects will help you gain a holistic view of the Qt framework.
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.
Section 1, Learn Qt 5, it 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.
Section 2, Mastering QT 5, you'll address all the challenges while developing cross-platform applications with the Qt framework. Through this learning path, you will have a better understanding of the Qt framework and the tools to resolve serious issues such as linking, debugging, and multithreading. It will also upskill you by teaching how to create a to-do style app by going via all stages for building a successful project.
Section 3, Qt 5 Projects, the project will be for industrial and agricultural sectors, to make sense of sensor data via a monitoring system. The apps should run seamlessly across devices and operating systems like Android, iOS, Windows, or Mac, and be cost-effective by integrating with existing web technologies. You take the role of lead developer and prototype the monitoring system. In doing so you’ll get to know Qt's Bluetooth and HTTP APIs, as well as the Charts and Web Engine UI modules. These projects will help you gain a holistic view of the Qt framework.
A good understanding of C++ language is highly recommended as the book is for the developers and programmers who want to build GUI-based applications. You will need any OS (Windows, Linux, or macOS) and any C++ compiler installed on your systems in order to get started.
You can download the example code files for this learning path from your account at www.packtpub.com. If you purchased this learning path 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
learning path
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 at https://github.com/PacktPublishing/Book-Name. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
html, body, #map { height: 100%; margin: 0; padding: 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:
[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
$ mkdir css
$ cd css
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: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the learning path title in the subject of your message. If you have questions about any aspect of this learning path, 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 learning path, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your learning path, 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.
Please leave a review. Once you have read and used this learning path, 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.
Build modern, responsive cross-platform desktop applications with Qt, C++, and QML
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 various techniques. We will cover the following topics:
Installing Qt
Maintaining your installation
Qt Creator
Scratchpad project
qmake
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
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:
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.
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.
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.
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.
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:
Issues displays 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.
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:projectsqt, while I use ~/projects/qt on Linux and Mac OS. Create this folder wherever works for you.
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:projectsqtscratchpadamazingcode. 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:projectsqt 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.
In this chapter, we downloaded, installed, and configured Qt. We’ve taken a whirlwind tour of the Qt Creator IDE, played with its options, and seen how to edit a variety of files with it. We’ve had a gentle introduction to qmake and seen how absurdly simple creating projects can be, demystifying things in the process. Finally, we built our debut project up from scratch (weak pun intended) and got the obligatory Hello World message on screen.
In Chapter 2, Project Structure, we will build on these basics and set up our main solution.
In this chapter, we will create a new multiproject solution that will be the foundation of our example application. We will apply a Model View Controller pattern, separating the user interface and business logic. We will also introduce Qt’s unit testing framework—QtTest—and demonstrate how to integrate it into our solution. We will cover these things in this chapter:
Projects, MVC, and unit testing
Creating a library project
Creating a unit tests project
Creating a user interface project
Mastering MVC
The QObject base class
QML
Controlling project output
The scratchpad application we built in the previous chapter is a Qt project, represented by a .pro file. In a business environment, technical solutions are generally developed as part of company initiatives, and these initiatives are generally also called projects. To try and minimize confusion (and the number of times the word project appears!), we’ll use project to mean a Qt project defined by a .pro file and the word initiative to refer to projects in the business sense.
The initiative we will work on will be a generic client management system. It will be something that can be tweaked and re purposed for multiple applications—for a supplier managing customers, a health service managing patients, and so on. It will perform common tasks found over and over in real-world Line of Business (LOB) applications, principally adding, editing, and deleting data.
Our scratchpad application is entirely encapsulated within a single project. For smaller applications, this is perfectly viable. However, with larger code bases, particularly with several developers involved, it often pays to break things up into more manageable pieces.
We will be using a super lightweight implementation of the Model View Controller (MVC) architectural pattern. If you haven’t come across MVC before, it is primarily used to decouple business logic from the user interface. The user interface (View) relays commands to a switchboard style class (Controller) to retrieve the data and perform actions it needs. The controller in turn delegates the responsibility for the data, logic, and rules to data objects (Models):
The key is that the View knows about the Controller and the Model, as it needs to send commands to the Controller and display the data held in the Model. The Controller knows about the Model as it needs to delegate work to it, but it doesn’t know about the View. The Model knows nothing about either theController or the View.
A key benefit of designing the application this way in a business environment is that dedicated UX specialists can work on the views while programmers work on the business logic. A secondary boon is that because the business logic layer knows nothing about the UI, you add, edit, and even totally replace user interfaces without affecting the logic layer. A great use case would be to have a “full fat” UI for a desktop application and a companion “half fat” UI for a mobile device, both of which can use the same business logic. With all this in mind, we will physically segregate our UI and business logic into separate projects.
We will also look at integrating automated unit tests into our solution. Unit testing and Test Driven Development (TDD) has really grown in popularity in recent times and when developing applications in a business environment, you will more than likely be expected to write unit tests alongside your code. If not, you should really propose doing it as it holds a lot of value. Don’t worry if you haven’t done any unit testing before; it’s very straightforward, and we’ll discuss it in more detail later in the book.
Finally, we need a way to aggregate these subprojects together so that we don’t have to open them individually. We will achieve this with an umbrella solution project that does nothing other than tying the other projects together. This is how we will lay out our projects:
In the previous chapter, we saw how easy it is to set up a new project just by creating a few text files. However, we’ll create our new solution using Qt Creator. We will use the new project wizard to guide us through creating a top-level solution and a single subproject.
From the top menu, select File > New File or Project and then Projects > Other Project > Subdirs Project and click on Choose…:
Subdirs Project is the template we need for our top-level solution project. Give it the name cm and create it in our qt projects folder:
On the Kit Selection pane, check the Desktop Qt 5.10.0 MinGW 32bit kit we installed. Feel free to select additional kits you want to try out if you have them installed, but it’s not necessary. Click on Next:
As discussed, version control is beyond the scope of this book, so in the Project Management pane, select None from the Add to version control dropdown. Click on Finish & Add Subproject:
We’ll add the user interface project as the first subproject. The wizard follows more or less the same pattern as the steps we've just followed, so perform the following:
Select
Projects
>
Application > Qt Quick Application - Empty and click on
Choose...
In the
Project Location dialog, give it the name
cm-ui
(for Client Management - User Interface), leave the location as our new
cm
folder, and click on
Next.
In the
Define Build System dialog, select the build system
qmake and click on
Next.
In the
Define Project Details dialog, leave the default minimal Qt version of
QT
5.9 and the
Use Qt Virtual Keyboard box unchecked then click on
Next.
In the
Kit Selection dialog, pick the
Desktop Qt 5.10.0 MinGW 32bit kit plus any other kits you wish to try and click on
Next.
Finally, in the
Project Management dialog, skip version control (leave it as
<None>) and click on
Finish.
Our top-level solution and UI projects are now up and running, so let’s add the other subprojects. Add the business logic project next, as follows:
In the
Projects pane, right-click on the top-level
cm
folder and select
New Subproject….
Select
Projects > Library > C++ Library and click on
Choose....
In the
Introduction and Project Location dialog, pick
Shared Library as the Type, name it
cm-lib
, create it in
<Qt Projects>/cm
, and then click on
Next.
In the
Select Required Modules dialog, just accept the default of
QtCore and click on
Next.
In the
Class Information
dialog, we get the opportunity to create a new class to get us started. Give the class name
Client
, with the
client.h
header file and the
client.cpp
source file, and then click on
Next.
Finally, in the
Project Management dialog, skip version control (leave it as
<None>) and click on
Finish.
Finally, we will repeat the process to create our unit testing project:
New Subproject....
Projects > Other Project > Qt Unit Test.
Project name
cm-tests
.
Include
QtCore and
QtTest.
Create the
ClientTests
test class with the
testCase1
test slot and the
client-tests.cpp
filename. Set the Type as
Test and check
Generate initialization and cleanup code.
Skip version control and
Finish.
That was a lot of dialog boxes to get through, but we’ve now got our skeleton solution in place. Your project folders should look as follows:
We’ll now take a look at each project in turn and make some tweaks before we start adding our content.
