Qt 5 Projects - Marco Aldo Piccolino Boniforti - E-Book

Qt 5 Projects E-Book

Marco Aldo Piccolino Boniforti

0,0
35,99 €

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

Mehr erfahren.
Beschreibung

Design, build, and deploy powerful applications with amazing user interfaces on embedded, mobile, and desktop platforms

Key Features

  • Easily compile, run, and debug your applications from the powerful Qt Creator IDE
  • Future-proof your applications with Qt Test and modern architecture principles
  • Build multi-platform projects that target Android, iOS, Windows, macOS, Linux, and more

Book Description

Qt is a professional cross-platform application framework used across industries like automotive, medical, infotainment, wearables, and more. In this book you’ll initially create a to-do style app by going via all stages for building a successful project. You'll learn basics of Qt's C++ and QML APIs, test-driven development with Qt Test, application architecture, and UIs with Qt Quick & Quick Controls 2.

Next, you’ll help two startups build their products. The first startup, Cute Comics, wants to help independent comic creators with a suite of apps that let them experiment with comic pages, image composition, comic dialogues, and scene descriptions. While developing these apps you’ll deepen your knowledge of Qt Quick's layout systems, and see Qt 3D and Widgets in action.

The second startup, Cute Measures, wants to create apps 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.

What you will learn

  • Learn the basics of modern Qt application development
  • Develop solid and maintainable applications with BDD, TDD, and Qt Test
  • Master the latest UI technologies and know when to use them: Qt Quick, Controls 2, Qt 3D and Charts
  • Build a desktop UI with Widgets and the Designer
  • Translate your user interfaces with QTranslator and Linguist
  • Get familiar with multimedia components to handle visual input and output
  • Explore data manipulation and transfer: the model/view framework, JSON, Bluetooth, and network I/O
  • Take advantage of existing web technologies and UI components with WebEngine

Who this book is for

This book is for developers who want to successfully build and maintain cross-platform applications with advanced UI and connectivity features. Basic knowledge of C++ is required.

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:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 364

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.



Qt 5 Projects

 

 

 

 

 

 

Develop cross-platform applications with modern UIs using the powerful Qt framework

 

 

 

 

 

 

 

 

Marco Piccolino

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Qt 5 Projects

 

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: Arun NadarTechnical Editor: Surabhi KulkarniCopy Editor: Safis EditingProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Jason MonteiroProduction Coordinator: Shantanu Zagade

First published: February 2018

Production reference: 1210218

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

ISBN 978-1-78829-388-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

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.

I am grateful to the technical reviewers, Juergen Bocklage-Ryannel and Pierre-Yves Siret, for their insightful comments and thought-provoking suggestions. I would also like to thank Siddharth Mandal, Arun Nadar, Surabhi Kulkarni, and the whole Packt team that worked on the book, improving it in various ways, from code to language. Finally, I would like to thank my colleagues, my parents, and my wife Silvia for their support.

About the reviewers

Jürgen Bocklage-Ryannel worked as a Qt Trainer and Training Manager at Trolltech and Nokia. Before Qt, he worked as software architect and trainer at Siemens/DIGIA for Symbian OS. He is passionate Scrum Master and agile evangelist, and deeply rooted into the Qt community. He is the co-author of the online QML book and nowadays call himself a UX enabler —he understands, the mechanics of what makes a good user experience. He loves to be at the crossing point of technology and design. He currently works for Pelagicore/Luxoft as UX Enabler for the automotive industry.

 I would like to thank Marco Piccolino for inviting me to review his Qt 5 book. He has a unique view on the problems and is spot on with his analysis. It was fun to work with him, and I am looking forward to the next great things to come out of his mind. Additional, I would like to thank my wife, Olga, and my little son, Matteo, for supporting me in my review tasks. Thanks.

Pierre-Yves has been using Qt for the past 9 years, first enjoying it personally and now using it professionally for 4 years.

Working on desktop and mobile applications ranging from medical practice software to home automation apps, he quickly became a fan of QML for its clean and declarative syntax. Always willing to help others, you might have already met him on IRC or StackOverflow as Grecko. Don't forget to check Pierre-Yves' open source projects (oKcerG on GitHub), they might help you in your Qt journey.

 

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

Title Page

Copyright and Credits

Qt 5 Projects

PacktPub.com

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

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

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

"With great power, there must also come -- great responsibility!"
– A friend of Spider-Man

The projects I have for you are not just meant to show you how powerful and easy it is to build complete applications and rich user interfaces with Qt (you could find out that on your own, I assume you are smart), but first and foremost, they are meant to show you how to do that by writing maintainable code that you'll want to touch and expand upon without regret any time you feel like it. And that requires a little experience. In the end, that's what I am offering you above anything else: my experience as a software developer who uses Qt daily to fulfill my customers' and my own needs.

Every experienced storyteller will tell you that we humans pass along stories because they help us survive. That's what I am going to do in this book, too. I'll tell you the story of two start-ups that need you to help them develop their products. I am confident that you'll make it through and complete the projects because you have a clear purpose, and because this book will provide you with the roadmaps to get there.

Whether you are planning a consumer-oriented digital product, or a product ecosystem intended for businesses, you'll find out which Qt building blocks are best suited for your endeavor, and which Qt application programming interfaces (APIs) you could use to achieve your goals in a time-efficient and future-proof manner.

In every project, we will start with the user's needs by drawing knowledge from the principles of behavior-driven development, test-driven development, clean coding and clean crchitecture. You might at first find this kind of approach daunting and verbose. However  I promise, the experience will be increasingly rewarding, and the process justified. To make sure you put your best foot forward, make sure you read the following sections. Have a good journey!

Who this book is for

This book is meant for developers who want to design feature-rich, customer and business-oriented applications and dynamic graphical user interfaces, and deploy them seamlessly to embedded, mobile, server, and desktop devices. Furthermore, it is meant for developers who want to be able to grow and maintain those applications without getting frustrated or outright mad because of unnecessary code complexity.

The book is goal and project-oriented, and requires some working experience with C++ 11 and JavaScript programming, plus the willingness to explore and embrace test-driven development and current best practices in software design and implementation.

What this book covers

Chapter 1, Writing Acceptance Tests and Building a Visual Prototype, describes a simple personal app project (What's in my fridge?) both in terms of the problems it tries to solve and the solutions that an application helps come up with. We write acceptance tests with Qt Test to ensure that the main usage scenarios are met. We introduce the Qt Quick Designer and Qt Quick Controls as an effective means of prototyping and implementing user interfaces.

Chapter 2, Defining a Solid and Testable App Core, shows how the powerful Qt object model (especially signals, slots, and properties) makes it easy to design the application's architecture by means of well-defined layers, and also makes it easy to write terse and reusable code. In this chapter, we implement the scenarios and business objects that we came up with in the previous chapter, and learn about the relative merits of Qt's QML and C++ APIs.

Chapter 3, Wiring User Interaction and Delivering the Final App, shows how to add the UI on top of the business logic implemented in the previous chapter. We show how easy it is to change UI technology depending on the target platform without altering the underlying logic. We also introduce platform-specific guidelines to deploy the app on common desktop and mobile systems.

Chapter 4, Learning About Laying Out Components by Making a Page Layout Tool, uncovers the flexibility of the Qt Quick framework by building an app that makes extensive use of different and dynamic item positioning methods. We explore the Qt Quick module, discover the QML Camera API, and learn how to load images from the filesystem into the UI.

Chapter 5, Creating a Scene Composer to Explore 3D Capabilities, dives into Qt 3D, one of the latest Qt UI APIs. We build a UI that mixes 2D and 3D scenes, and set up a 3D scene whose parameters can be manipulated via the 2D UI controls. We see how to add and remove 3D models from the scene, and save a picture from the current scene with just a few lines of code.

Chapter 6, Building an Entity-Aware Text Editor for Writing Dialogues, is centered on building a productivity-focused app thanks to Qt Widgets, a set of mature, desktop-oriented UI components that cover a wide range of needs. We write a specialized text editor with custom highlighting, whose contents can be modified by both typing and widget controls. We then export the formatted text to PDF. In this chapter we also introduce Qt's model/view paradigm.

Chapter 7, Sending Sensor Readings to a Device with a Non-UI App, explores how to create a command-line based application that gathers generic sensor data and makes it available to other devices via a device-to-device Bluetooth connection.

Chapter 8, Building a Mobile Dashboard to Display Real-Time Sensor Data, unravels how to develop an application that receives the sensor readings transmitted in the previous chapters, and displays them in nice-looking charts by implementing a QML UI with Qt Charts.

Chapter 9, Running a Web Service and an HTML5 Dashboard, shows how to create an application that generates fake sensor data over time and exposes it via a REST web service. We develop an extended version of the app from the previous chapter, by using Qt WebEngine to display the content via web sockets. We leverage one of the existing JavaScript chart libraries to display the data, to make sure that the same HTML5 UI could be in future served to a standard web browser.

Appendix, Additional and Upcoming Qt Features, briefly introduces additional important Qt features that were not mentioned in the projects, as well as recent and upcoming features that were introduced after Qt 5.9 Long Term Support.

To get the most out of this book

In this book, I assume you already have a basic understanding of common data structures and algorithms. You should also be familiar with the principles of object-oriented programming (OOP). A working knowledge of C++11 is required for all projects. JavaScript 5 is required for the projects involving the QML language.

This book does not explicitly cover all the steps required for having a Qt distribution and the Qt Creator IDE up and running. You will find many resources covering this kind of information in the official Qt documentation, in other Packt titles, and in many tutorials available online. I will just show you where to download Qt at the right time.

The book is based on Qt 5.9 Long Term Support as this is, at the time of writing, the version that is supported for the longest time, as its name suggests. However, any later minor version (5.x) will be compatible with the code shown here.

If you ever need help or get stuck, which sooner or later will happen despite all efforts I took to provide you with everything you need, remember that one of Qt's best features is its community. Here are the resources I think you should familiarize yourself with before starting with the book:

The official 

forum

(

https://forum.qt.io/

), where many newcomers and some experts share their knowledge.

The

IRC channels

(

https://wiki.qt.io/Online_Communities#IRC_channels

), frequented by many Qt developers and users with various levels of experience. A good place to start is the

#qt

channel.

The

Interest mailing list

(

http://lists.qt-project.org/mailman/listinfo/interest

), which is very useful especially for getting answers to less common questions.

The

QtMob

Slack community (

http://slackin.qtmob.org

), which is mostly dedicated to the development of Qt apps on common mobile platforms.

When it comes to additional sources of information, here are a few recommendations:

Qt's

official documentation

(

http://doc.qt.io

), a very comprehensive source of information about Qt APIs and general concepts. At times it might be hard to find what you are looking for — if you are in doubt, ask on one of the channels from the previous list. The documentation is also integrated into Qt Creator, and is also available for documentation browsers such as Dash and Zeal.

Qt's

examples

, available with your distribution and accessible from Qt Creator.

The

training videos

 (

https://www.qt.io/qt-training-materials/

) and

self-study pack

 (

https://www.qt.io/qt-training-materials/

) at

qt.io

.

The

Qt Company's blog

(

http://blog.qt.io/

), the main source for announcements of Qt releases and upcoming webinars, also offering also technology-related posts on current or upcoming features, and HowTos.

KDAB's blogs

(

https://www.kdab.com/category/blogs/

), a wealth of articles about various topics, including data structures, OpenGL, Qt 3D, Qt for Android, and more. KDAB is one of Qt's main contributors and a consultancy firm.

ICS's blog

(

https://www.ics.com/blog

)

and webinars

, covering various topics, including Qt basics. ICS is Qt consultancy firm particularly active in North America.

The

QML Book 

(

https://qmlbook.github.io/

), an extensive free resource covering QML and Qt Quick.

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/Qt-5-Projects. 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 athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here:

https://www.packtpub.com/sites/default/files/downloads/Qt5Projects_ColorImages.pdf.

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.

Writing Acceptance Tests and Building a Visual Prototype

Qt (pronounced like the English adjective cute) is just that, incredibly cute.

If you start working with Qt extensively, you will hardly find another piece of software that tickles your imagination and creativity while catering for your professional needs as much as Qt does. It's got it all. As a professional, you will certainly value its more than 20 years of maturity, solid release cycle, and backward compatibility promises. As a hobbyist, you will fall for its cutting-edge features. In both cases, you will appreciate its smooth and powerful graphic capabilities, extensive collection of general purpose programming libraries, unrivaled cross-platform support, great all-around tooling, good documentation, and thriving community. Furthermore, you will treasure its concise syntax with the QML and JavaScript languages, and its horsepower and expressiveness with the C++ language, as well as its language bindings for Python, Go, and more.

Given its magnificence, you will be tempted to just jump into coding and learn things as you go along. I know how it goes; I went through it, and now I am here, and I probably have something to say about it. Do I regret having taken the hard route? Well, yes and no. Yes, because it took me a few complete app remakes to get things reasonably right; no, because, of course, I learned a lot along the way. At least, I learned exactly (and this is still an ongoing process) what not to do with the many facilities that Qt has to offer.

On the other hand, you have this book in front of you; it probably means that you didn't want to begin this journey all by yourself, right? Maybe you did, and you soon realized that you needed a travel mate. Well, here I am, your new travel mate. Where shall we start from? I can see you now; you are all excited. However, before we jump in, let us first look at the larger picture.

You won't be able to dwell in the house you are trying to build if you don't first sit down to do your planning and research before laying the very first brick. You can take care of how the mirror in the bathroom will look later on. You just need to start with the most important thing, and that is a high-level plan that provides you with an overview about what you want to build.

Don't come to me with an idea, come to me with a plan

One summer, I had the pleasure to be mentored by a guy called Shai. From what I gathered, Shai was probably a serial entrepreneur, certainly an investor, and most definitely an excellent trainer.

One of the things I learned from him during the brief summer school, which he was leading, is that you have to drink plenty of water for your body to function properly and your ideas to flow.

Another thing that I learned from him is that in entrepreneurship, just as in software development, plans are far superior to ideas. Having a good idea is essential, but it is not enough. You need a plan. This is what he used to say to soon-to-be entrepreneurs who went to him to present their shiny, groundbreaking ideas:

"Don't come to me with an idea. Come to me with a plan."

Exploration is one thing, learning to achieve expertise is another. While exploring, you taste a bit of this and a bit of that, without a clear purpose or plan — that is, without a blueprint. Exploration is good and necessary, but it has its limits. If you want to just explore what Qt does, there is plenty of very good material covering that:

Other Qt-related Packt titles (

https://www.packtpub.com/all?search=qt

)

The official Qt documentation (

http://doc.qt.io/

)

Examples and tutorials included in Qt Creator (Qt's official IDE) (

http://doc.qt.io/qt-5.9/qtexamplesandtutorials.html

)

Tutorial videos and webinars available from many core Qt contributors

User-contributed material of all kinds

I'll give you specific pointers to many of these resources wherever needed. I also covered many of these in the Preface.

In this book, I will follow a strong goal, project, and scenario-based approach, showing you how to apply current best practices of software development by leveraging what Qt has to offer. I'll provide you with some ready-made plans in the hope that you will come up with even better ones for your own projects, be it a hobby project or a business-related endeavor. We will use an outside-in approach, starting from clear functional goals all the way inwards to implementation details. Enough said! Let's get started with the first project.

In this chapter, we will lay the foundations for a simple to-do list-like application by dealing with its intended goals, main scenarios and usecases, and UI prototyping. This will give you a good introduction to how you can perform Behavior-Driven Development (BDD) with the QtTest framework, Qt's object model, introspection features and signals/slots, an overview of available Qt rendering frameworks, and UI prototyping with Qt Creator's Quick Designer.

The problem — what's in my fridge?

If you are an out-of-town student, and even if you are not, you may know all too well the sensation of desolation that often surfaces when you open the fridge and find empty shelves. Look! A lonely slice of cheese is greeting you and asking for your companionship. Oh, and that thing nearby probably used to be an apple a few months back. Dammit! You were working on your much-beloved personal project and completely forgot to buy groceries, and now the shops are closed, or are too far away to bother going.

The solution — an app idea

No problem, right? If you are lucky, there is yet another cheap pizza waiting for you in the deep freeze, otherwise you will be once again eating some cheap takeaway.

Wrong! If this becomes the normal solution, in a few years' time, your liver will curse you in ways you cannot even imagine. The real solution is this: don't be lazy, take good care of yourself. Remember Shai? Besides drinking plenty of water, you should also eat stuff that is good for your body (at the entrepreneurship camp, apart from great catering, next to the water bottles, there was a pile of apples, and both the water bottles and the apples were freely accessible all day long).

How could you start implementing this sensible advice? One good thing to do would be to keep track of your food resources and intervene before it's too late. Of course, you could do that with just a pencil and paper, but you are a nerd, right? You need an app, and a cute one! Well, here you go; finally, your personal project will contribute to your health rather than taking its share from it.

The plan — start from user stories

OK, we need an app. Let's start building the user interface (UI).

But what if we wanted the same application to have a graphical UI and at the same time leave the door open to add a console-based UI, or even a voice interface in the future? We need a way to specify our app's functional requirements before describing how it will look, or how it will be delivered to our users. Also, it would be very useful if we could verify that those requirements are actually met within the code. Even better, in an automatic fashion, by means of what are usually labeled as acceptance tests, using procedures that verify that all or most of our app's usage scenarios are actually working as expected. We can achieve that by starting from user stories.

Writing features and scenarios

Behavior-Driven Development (BDD) is a way of developing software that encourages starting from user stories (or features) and then moving on from those to system implementation. According to Dan North, one of BDD's initiators, a feature is a description of a requirement and its business benefit, and a set of criteria by which we all agree that it is “done”. The main goal of BDD is for project stakeholders (customers, business people, project managers, developers, and people who work in quality assurance) to share common expectations about a feature. The description of how a feature should behave in a specific context of preconditions and outcomes is called a scenario. All scenarios outlined for a specific feature constitute its acceptance criteria: if the feature behaves as expected in all scenarios, it can be considered as done. For a clear and synthetic introduction to BDD take a look at https://dannorth.net/whats-in-a-story/.

BDD is now a widespread approach, and some standards exist to make it easier for stakeholders to share the description of scenarios and their verification. Gherkin (https://github.com/cucumber/cucumber/wiki/Gherkin) is such a standard: a human-readable language, which can also be used by a software system to link usage expectations to system instructions by means of acceptance tests, which strictly follow the structure of scenarios.

The following is what a Gherkin feature specification (a user story outlined as a set of scenarios) looks like:

Feature: Check available groceries I want to check available groceries in my fridge to know when to buy them before I run out of them Scenario: One or more grocery items available Given there is a list of available grocery items And one or more grocery items are actually available When I check available groceries Then I am given the list of available grocery items And the grocery items are ordered by name, ascending Scenario: No grocery items available Given there is a list of available grocery items And no grocery items are actually available When I check available groceries Then I am informed that no grocery items are available And I am told to go buy some more

The Check available groceries feature, which encapsulates assumptions and expected outcomes relative to a specific user action, is analyzed in two scenarios, which show how the outcomes vary depending on different assumptions (one or more grocery items are available versus no grocery items are available).

I guess you can figure out the basic structure of a scenario in its commonest form: one or more Given clauses describing preconditions, one or more  When clauses describing user-initiated or system-initiated actions, and one or more Then clauses describing expected outcomes.

Specifying the behavior of your application in terms of feature scenarios has many benefits, as follows:

The specification can be understood even by nontechnical people (in the case of

What's in my fridge

, this means that your family members can offer their expertise in taking care of home food provisions to help you sketch out the most important features for the app).

There are quite a few libraries around that can help you link the specification to the actual code and can then run the gherkin feature file and check whether the preconditions, actions, and expected outcomes (collectively known as

steps

) are actually implemented by the system (these constitute the

acceptance tests

for a feature).

You need, either individually or as a group of stakeholders, to actually sit down and write the acceptance criteria for a feature in full before writing any code that relates to it. By doing so, you often find out early on about any inconsistencies and corner cases you would have otherwise ignored.

Does Qt provide off-the-shelf support for gherkin-style feature descriptions and for writing automated acceptance tests? Currently, it doesn't. Is there any way to implement this very sensible approach to software development in Qt projects? Yes, there is.

I know of at least the following ways:

You can download and build the

cucumber-cpp

(

https://github.com/cucumber/cucumber-cpp

) project, which also contains a Qt driver, and try and link it to your project. I haven't tested this way yet, but if you are braver than I, you could give it a go.

You can buy a (admittedly, not cheap) license for

Froglogic Squish

(

https://www.froglogic.com/squish/editions/qt-gui-test-automation/

), a professional grade solution for many types of application testing, including BDD, which fully supports Qt.

You can write your acceptance tests with the Qt Test framework and give them a Gherkin-style structure. This is the approach I currently use in my projects, and in the next section I will show you a couple of ways to achieve this.

So, now that we have written our first feature, with as many as two scenarios, we are ready to dive into code, right?

Not really. How would you add grocery items to the list? How about removing them from the list when you take them out of the fridge? We'll first need to write those two other features at least, if we want to have a minimum viable product.

If you haven't done it yet, now is the time to download Qt for Application Development distribution and install it.There are a few options available, in terms of licensing (commercial, GPL, and LGPLv3), supported host (macOS, Windows, and Linux), target platforms (several available) and installation mode (online versus offline). Regarding licensing, take your time to make an informed choice, and ask a lawyer in case of doubt. For more information, take a look at the Qt Project's licensing page at http://doc.qt.io/qt-5/licensing.html. To download Qt with the online installer for your host platform, go to http://www.qt.io/download, choose one of the available options, and follow the installation instructions. The projects contained in this book are based on Version 5.9, which is a Long Term Support (LTS) version. For a smooth ride, you are encouraged to use the latest available bugfix release of version 5.9. If you are adventurous enough, you could also install a later version. The book's projects should still work with any later 5.x version, but please understand that they haven't been tested for that, so your mileage may vary.

Implementing scenarios as acceptance tests

As I mentioned in the preceding section, the standard Qt distribution does not give off-the-shelf support for BDD. However, it does provide a rich testing framework (Qt Test), which can be leveraged to implement most kinds of tests, from unit tests to acceptance tests. In the coming sections, we will implement our first acceptance test with Qt Test. First, however, let us spend a few words on project organization and introduce the two main programming languages currently used in the Qt world: C++ and QML.

Our project structure

Throughout the book, all online documentation links will point to Version 5.9 for consistency. If you want or need to access the latest version of a document, you can just remove the minor version from the URL, as follows: http://doc.qt.io/qt-5.9/qobject.html > http://doc.qt.io/qt-5/qobject.html. Similarly, a later minor version can be accessed by changing the minor version in the URL: http://doc.qt.io/qt-5.10/qobject.html

This book uses the Qt Creator IDE for project development, together with the QMake build and project organization system. Both tools are included in the default precompiled Qt distributions. I will give you hints on how to carry out project-specific operations with both Qt Creator and QMake. For further details on how to operate them, you can look at other specific Packt titles, as well as the official Qt documentation for Qt Creator (http://doc.qt.io/qtcreator/) and QMake (http://doc.qt.io/qt-5.9/qmake-manual.html).

Both Qt Creator and Qt support other build and project organization systems beyond QMake. The most widespread are Qbs (pronounced as cubes, which is part of the Qt Project, http://doc.qt.io/qbs/) and CMake (http://doc.qt.io/qtcreator/creator-project-cmake.html). The deep integration with Qt Creator makes QMake the best choice to get started. You can take a look at using the other systems if your workflow benefits from it.