Mastering Qt  5 - Guillaume Lazar - E-Book

Mastering Qt 5 E-Book

Guillaume Lazar

0,0
34,79 €

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

Mehr erfahren.
Beschreibung

Qt 5.11 is an app development framework that provides a great user experience and develops full capability applications with Qt Widgets, QML, and even Qt 3D. Whether you're building GUI prototypes or fully-fledged cross-platform GUI applications with a native look and feel, Mastering Qt 5 is your fastest, easiest, and most powerful solution. This book addresses various challenges and teaches you to successfully develop cross-platform applications using the Qt framework, with the help of well-organized projects.
Working through this book, you will gain a better understanding of the Qt framework, as well as the tools required to resolve serious issues, such as linking, debugging, and multithreading. You'll start off your journey by discovering the new Qt 5.11 features, soon followed by exploring different platforms and learning to tame them. In addition to this, you'll interact with a gamepad using Qt Gamepad. Each chapter is a logical step for you to complete in order to master Qt.
By the end of this book, you'll have created an application that has been tested and is ready to be shipped.

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

EPUB
MOBI

Seitenzahl: 563

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.



Mastering Qt 5Second Edition
Create stunning cross-platform applications using C++ with Qt Widgets and QML with Qt Quick
Guillaume Lazar
Robin Penea
BIRMINGHAM - MUMBAI

Mastering Qt 5 Second Edition

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 authors, 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:Larissa PintoContent Development Editor:Flavian VazTechnical Editor:Akhil NairCopy Editor:Safis EditingProject Coordinator:Devanshi DoshiProofreader:Safis EditingIndexer:Rekha NairGraphics:Jason MonteiroProduction Coordinator:Shraddha Falebhai

First published: December 2016 Second edition: August 2018

Production reference: 1230818

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

ISBN 978-1-78899-539-9

www.packtpub.com

To my sisters, Christine and Patricia. To my parents, Béatrice and Claude. To my fiancé, Sophie.

– Guillaume Lazar
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 authors

Guillaume Lazaris a software engineer living in France, near Paris. He has worked in different companies, from start-ups to multinationals, for the last 10 years. He took the opportunity to observe and learn many team organizations and technologies.

In 2014, he founded his own software development company at the age of 27. The current hierarchical organization that applies to most companies seems obsolete to him. With his own company, he wants to try a different approach.

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".

Working on this second edition of Mastering Qt 5 was a great pleasure. The Qt framework is constantly evolving and you can now enjoy this book using Qt 5.11. A lot of people help me to bring this new edition to life. The publisher team: Akhil Nair and Flavian Vaz. The reviewer team: Kévin Lemaire, Robin Penea, and Pavel Strakhov. By the way, Robin was also the co-author of the first edition in 2016 and this book owes him a lot.

Robin Peneahas been working in the software industry for a more than a decade. He worked in start-ups and large companies with many technologies that ranged from embedded software to web development. Armed with this experience, he wrote the Mastering Qt 5 book to spread what he loves the most about the programming craft: proper design and quality code. The teaching bug has bitten him, and he continues to share what he learned online using videos. When he is not tinkering with some new technology, he is either on a wall, rock-climbing, or playing music on his piano. You can reach him via Twitter @synapticrob.

This book would not have existed without Guillaume Lazar, my friend and co-author of the book. He was truly dedicated to the work. I thank our reviewers, Rohit Kumar Singh, Ray Rischpater, Quentin Canu, Christophe Dongieux, and Hugo Loi. Also my father, Calin, for always believing in me. Finally, for Flore, my girlfriend, who kept me sane during this endeavor.

About the reviewers

Pavel Strakhov is a software architect and developer from Russia. He started working with Qt in 2011 in Moscow Institute of Physics and Technology, where it was used to build scientific image processing software. He was highly active in the Qt section of StackOverflow, helping people learn Qt and solve issues. He also worked on Qt bindings for Rust. He is the main author of the book called Game Programming Using Qt 5 / Beginner's Guide / Second Edition published in 2018 by Packt.

Kévin Lemaire is a software engineer since 2011. He lives in the north of Paris since he was born. He first studied accountancy but has quickly been interested in how softwares were makes it easier and switched to IT studies. Now he gets to work in a full Microsoft environment: C++, C#, and WPF. He also is a MCP for SQL Server 2012.

Kévin works for Arc Informatique, a French SCADA provider. He is in charge of data consistency, which starts with the acquisition of industrial equipments, to its storage in files or databases, and data enhancement with reporting.

Kévin has always been fond of Japan. Firstly through anime, then to its music, which he spends time translating as a hobby. He is a dog person and adopted a lovely Shiba Inu.

I want to thank Stéphanie, my lovely wife, who supported me to spend some nights working on this book. I also want to thank Guillaume for trusting me with this review. This project was a way to try to transform a hobby into something more professional, which was still a lot of fun.

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

Mastering Qt 5 Second Edition

Dedication

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the authors

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

Conventions used

Get in touch

Reviews

Get Your Qt Feet Wet

Qt project basic structure

MainWindow structure

Qt Designer interface

Signals and slots

Custom QWidget

Adding a task

Using a QDialog

Distributing code responsibility

Emitting a custom signal using lambdas

Simplifying with the auto type and a range-based for loop

Summary

Discovering qmake Secrets

Designing a cross-platform project

Adding the Windows implementation

Adding the Linux implementation

Adding the macOS 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 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 devices

Creating a new album from a custom InputDialog

Loading images with an ImageProvider

Displaying thumbnails in GridView

Swiping through full resolution images

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!

Creating an SDK using the Qt Plugin system

Creating your plugins

Loading your plugins dynamically

Using the plugins inside the application

Discovering the Animation Framework

Making your thumbnails jump

Fading in the picture

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

Inter-process communication techniques

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 Multimedia and 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 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 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

Playing with Qt Gamepad

Styling QML with Qt Quick Controls 2

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

C++ is a powerful language. Coupled with Qt, you have in your hands a cross-platform framework that allies performance and ease of use. Qt is a vast framework that provides tools in many areas (GUI, threads, networking, and so on). 25 years after its inception, Qt continues to evolve and grow with each release.

This book aims to teach you how to squeeze the best out of Qt 5.11 with the new C++14 additions (lambdas, smart pointers, enum classes, and so on). These two technologies together bring you a safe and powerful development toolbox. Throughout the book, we try to emphasize a clean architecture that lets you create and maintain your application in a complex environment.

Each chapter is based on an example project that is the basis of all the discussion. Here are some tasters about what we will see in this book:

Uncover qmake secrets

Take a deep dive in

the model/view architecture and study how you can build a

complex application with this pattern

Study QML and Qt Quick applications in mobile

Develop Qt 3D components using QML and JavaScript

Show how to develop plugins and SDKs using Qt

Cover the multi-threading technologies provided by Qt

Build an IPC mechanism using sockets

Serialize data using XML, JSON, and binary format

Interact with a gamepad using Qt Gamepad

We'll cover all this and much, much more.

Note that you can take a look at Chapter 14, Qt Hat Tips and Tricks, whenever you want if you want to get some development candies and see some code snippets that might make your development more pleasurable.

And most importantly, have fun writing Qt applications!

Who this book is for

This book will appeal to developers and programmers who would like to build GUI-based applications. You should be fluent in C++ and the object-oriented paradigm. Qt knowledge is recommended but is not necessary.

What this book covers

Chapter 1, Get Your Qt Feet Wet, lays the fundamentals of Qt and refreshes your memory with a todo application. This chapter covers the Qt project structure, how to use the designer, basic principles of the signals and slots mechanism, and introduces new features of C++14.

Chapter 2, Discovering QMake Secrets, takes a deep dive in the heart of the Qt compilation system: qmake. This chapter will help you understand how it works, how to use it, and how you can structure a Qt application with platform-specific code by designing a system monitoring application.

Chapter 3, Dividing Your Project and Ruling Your Code, analyzes the Qt model/view architecture and how a project can be organized by developing a custom library with the core logic of the application. The project example is a persistent gallery application.

Chapter 4, Conquering the Desktop UI, studies the UI perspective of the model/view architecture with a Qt Widget application relying on the library completed in the previous chapter.

Chapter 5, Dominating the Mobile UI, adds the missing part of the gallery application with the mobile version (Android and iOS); the chapter covers it with the use of QML, Qt Quick controls, and QML / C++ interactions.

Chapter 6, Even Qt Deserves a Slice of Raspberry Pi, continues to the road on Qt Quick application with the Qt 3D perspective. This chapter covers how to build a 3D snake game targeted at the Raspberry Pi.

Chapter 7, Third-Party Libraries Without a Headache, covers how a third-party library can be integrated in a Qt project. OpenCV will be integrated with an image filter application that also provides a custom QDesigner plugin.

Chapter8, Animations, It's Alive, Alive!, extends the image filter application by adding animations and the ability to distribute a custom SDK to let other developers add their own filters.

Chapter 9, Keeping Your Sanity with Multithreading, investigates the multithreading facilities provided by Qt by building a multithreaded Mandelbrot fractal drawing application.

Chapter 10, Need IPC? Get Your Minions to Work, broadens the Mandelbrot fractal application by moving the calculation to other processes and managing the communication using sockets.

Chapter 11, Having Fun with Serialization, covers multiple serialization formats (JSON, XML, and binary) inside a drum machine application in which you can record and load sound loops.

Chapter 12, You Shall (Not) Pass with QTest, adds tests to the drum machine application and studies how the Qt Test frameworks can be used to make unit tests, benchmarking, and GUI events simulation.

Chapter 13, All Packed and Ready to Deploy, gives insights into how to package an application on all desktop OSes (Windows, Linux, and Mac) and mobile platforms (Android and iOS).

Chapter 14, Qt Hat Tips and Tricks, gathers some tips and tricks to develop with Qt with pleasure. It shows how to manage sessions in Qt Creator, useful Qt Creator keyboard shortcuts, how you can customize the logging, save it to disk, and much more.

To get the most out of this book

All the code in this book can be compiled and run from Qt Creator using Qt 5.11. You can do it from your preferred OS: Windows, Linux, or Mac.

About the mobile-specific chapters, either an Android or an iOS device works, but it is not mandatory (the simulator/emulator can be enough).

Chapter 6, Even Qt Deserves a Slice of Raspberry Pi, offers to build an application running on a Raspberry Pi. Although it is more fun if we can do it with a real Raspberry Pi, it is not necessary to have one to complete the chapter.

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/Mastering-Qt-5-Second-Editon. 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!

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.

Get Your Qt Feet Wet

If you know C++ but have never touched Qt, or if you have already made some intermediate Qt applications, this chapter will ensure that your Qt foundations are solid before studying advanced concepts in the following chapters.

We will teach you how to create a simple todo application using Qt Creator. This application will display a list of tasks that you can create/update/delete. We will cover the Qt Creator and Qt Designer interfaces, an introduction to the signal/slot mechanism, the creation of a custom widget with custom signals/slots, and its integration into your application.

You will implement a todo app using new C++14 semantics: lambdas, auto variables, and for loops. Each of these concepts will be explained in depth and will be used throughout this book.

By the end of this chapter, you will be able to create a desktop application with a flexible UI using Qt widgets and new C++ semantics.

In this chapter, we will cover the following topics:

Qt project basic structure

MainWindow structure

Qt Designer interface

Signals and slots

Custom

QWidget

C++14 lambda, auto, and for each

Qt Designer interface

Qt Designer is a major tool for developing Qt applications. This WYSIWYG editor will help you to easily design your GUI. If you switch between Edit mode and Design mode for the MainWindow.ui file, you will see the real XML content and the designer:

The designer displays several parts:

Form Editor (

1

): A visual representation of the form (empty for now)

Widget Box (

2

): Contains all the major widgets that can be used with your form

Object Inspector (

3

): Displays your form as a hierarchical tree

Property Editor (

4

): Enumerates the properties of the selected widget

Action Editor/Signal & Slots Editor (

5

): Handles toolbar actions and connections between your objects

It's time to embellish this empty window! Let's drag and drop a Label widget from the Display Widgets section on the form. You can change the name and the text properties directly from the Properties editor.

As we are making a todo application, we suggest these properties:

objectName

:

statusLabel

text

:

Status: 0 todo / 0 done

This label will later display the count of todo tasks and the count of tasks already done. Save, build, and start your application. You should now see your new label in the window.

You can now add a push button with those properties:

objectName

:

addTaskButton

text

:

Add task

You should get a result close to the following:

You can edit the text property of a widget directly on your form by double-clicking on it!

The design of the MainWindow.ui file is ready, we can now study the signals and slots.