39,59 €
Qt is the leading cross-platform toolkit for all significant desktop, mobile, and embedded platforms and is becoming popular by the day, especially on mobile and embedded devices. It's a powerful tool that perfectly fits the needs of game developers. This book will help you learn the basics of Qt and will equip you with the necessary toolsets to build apps and games.
The book begins by how to create an application and prepare a working environment for both desktop and mobile platforms. You will learn how to use built-in Qt widgets and Form Editor to create a GUI application and then learn the basics of creating graphical interfaces and Qt's core concepts.
Further, you'll learn to enrich your games by implementing network connectivity and employing scripting. You will learn about Qt's capabilities for handling strings and files, data storage, and serialization.
Moving on, you will learn about the new Qt Gamepad module and how to add it in your game and then delve into OpenGL and Vulcan, and how it can be used in Qt applications to implement hardware-accelerated 2D and 3D graphics. You will then explore various facets of Qt Quick: how it can be used in games to add game logic, add game physics, and build astonishing UIs for your games.
By the end of this book, you will have developed the skillset to develop interesting games with Qt.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 859
Veröffentlichungsjahr: 2018
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.
Acquisition Editor: Shweta PantContent Development Editor:Flavian VazTechnical Editor: Akhil NairCopy Editor:Shaila KusanaleProject Coordinator:Devanshi DoshiProofreader:Safis EditingIndexer:Rekha NairGraphics:Jason MonteiroProduction Coordinator:Aparna Bhagat
First published: January 2016 Second edition: April 2018
Production reference: 1240418
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78839-999-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.
Pavel Strakhovis 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. During 2012-2015, he was highly active in the Qt section of StackOverflow, helping people learn Qt and solve issues. In 2016, he started working on Qt bindings for Rust language.
Witold Wysota is a software architect and developer living in Poland. He started his adventure with Qt in 2004 and, since then, it has become his main area of expertise.
He is an active trainer and consultant in Qt, C++, and related technologies in both commercial and academic environments.
In real life, he is a passionate adept of Seven Star Praying Mantis, a traditional style of Chinese martial arts.
Lorenz Haas, a passionate programmer, started his Qt career with Qt 3. He immersed himself in this framework, became one of the first certified Qt developers and specialists, and turned his love for Qt into his profession.
Lorenz is now working as a lead software architect. He mainly develops machine controls and their user interfaces as well as general solutions for the industry sector.
Years ago, he started contributing to Qt Creator and Qt. He added a couple of refactoring options that you probably rely on regularly if you use Qt Creator. He is also the author of the Beautifier plugin.
Julien Déramond is a software developer living in Paris, France. He started his career developing C++ web services until he entered the embedded world via the Orange set-top boxes in 2012. Specialized in QML, he mainly prototypes and develops user interfaces with designers. Recently, he started contributing to Qt, especially in finding bugs and proposing patches for the QML JS Reformater of Qt Creator. When he is not writing code, he enjoys traveling and drawing.
Simone Angeloni is a software engineer with over 13 years of experience in C++ and a skillset including cross-platform development, embedded systems, multi-threading, user interfaces, network communication, databases, web applications, game development, and visual design.
He is currently a senior software engineer in the R&D dept of Nikon Corporation, and he is developing software/hardware solutions to control robots used in the motion picture industry.
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.
Title Page
Copyright and Credits
Game Programming Using Qt 5 Beginner's Guide 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
Introduction to Qt
A journey through time
The cross-platform programming
Supported platforms
GUI scalability
Qt versions
Structure of Qt framework
Qt Essentials
Qt Add-ons
qmake
Modern C++ standards
Choosing the right license
An open source license
A commercial license
Summary
Installation
Installing the Qt SDK
Time for action – Installing Qt using an online installer
What just happened?
Qt Creator
Qt Creator's modes
Setting up compilers, Qt versions, and kits
Time for action – Loading an example project
Qt documentation
Time for action – Running the Affine Transformations project
What just happened?
Summary
Qt GUI Programming
Creating GUI in Qt
Time for action – Creating a Qt Widgets project
What just happened?
Design mode interface
Time for action – Adding widgets to the form
Layouts
Time for action – Adding a layout to the form
Signals and slots
Creating signals and slots
Connecting signals and slots
Old connect syntax
Signal and slot access specifiers
Time for action – Receiving the button-click signal from the form
What just happened?
Automatic slot connection and its drawbacks
Time for action – Changing the texts on the labels from the code
Creating a widget for the tic-tac-toe board
Choosing between designer forms and plain C++ classes
Time for action – Creating a game board widget
What just happened?
Automatic deletion of objects
Time for action – Functionality of a tic-tac-toe board
Time for action – Reacting to the game board's signals
What just happened?
Advanced form editor usage
Time for action – Designing the game configuration dialog
Accelerators and label buddies
The tab order
Time for action – Public interface of the dialog
Polishing the application
Size policies
Protecting against invalid input
Main menu and toolbars
Time for action – Creating a menu and a toolbar
What just happened?
The Qt resource system
Time for action – Adding icons to the project
Have a go hero – Extending the game
Pop quiz
Summary
Custom 2D Graphics with Graphics View
Graphics View architecture
Time for action – Creating a project with a Graphics View
What just happened?
Coordinate systems
The item's coordinate system
The scene's coordinate system
The viewport's coordinate system
Origin point of the transformation
What just happened?
Have a go hero – Applying multiple transformations
Parent–child relationship between items
Time for action – Using child items
Have a go hero – Implementing the custom rectangle as a class
Conversions between coordinate systems
Overview of functionality
Standard items
Anti-aliasing
Pens and brushes
Item selection
Keyboard focus in graphics scene
Painter paths
Time for action – Adding path items to the scene
Z-order of items
Ignoring transformations
Time for action – Adding text to a custom rectangle
Finding items by position
Showing specific areas of the scene
Saving a scene to an image file
What just happened?
Have a go hero – Rendering only specific parts of a scene
Custom items
Time for action – Creating a sine graph project
Time for action – Creating a graphics item class
What just happened?
Events
Time for action – Implementing the ability to scale the scene
What just happened?
Time for action – Taking the zoom level into account
Time for action – Reacting to an item's selection state
What just happened?
Time for action – Event handling in a custom item
Time for action – Implementing the ability to create and delete elements with mouse
Time for action – Changing the item's size
Have a go hero – Extending the item's functionality
Widgets inside Graphics View
Optimization
A binary space partition tree
Caching the item's paint function
Optimizing the view
OpenGL in the Graphics View
Pop quiz
Summary
Animations in Graphics View
The jumping elephant or how to animate the scene
The game play
Time for action - Creating an item for Benjamin
The playing field
Time for action - Making Benjamin move
What just happened?
Parallax scrolling
Time for action - Moving the background
What just happened?
Have a go hero - Adding new background layers
The Animation framework
Properties
Time for action - Adding a jump animation
Property animations
Time for action - Using animations to move items smoothly
What just happened?
Have a go hero - Letting the item handle Benjamin's jump
Time for action - Keeping multiple animations in sync
What just happened?
Chaining multiple animations
Adding gamepad support
Working with gamepads in Qt
Time for action - Handling gamepad events
Item collision detection
Time for action - Making the coins explode
What just happened?
Finishing the game
Have a go hero - Extending the game
A third way of animation
Pop quiz
Summary
Qt Core Essentials
Text handling
String encodings
QByteArray and QString
Using other encodings
Basic string operations
The string search and lookup
Dissecting strings
Converting between numbers and strings
Internationalization
Using arguments in strings
Regular expressions
Time for action – A simple quiz game
What just happened?
Extracting information out of a string
Finding all pattern occurrences
Containers
Main container types
Convenience containers
Allowed item types
Implicit sharing
Pointer invalidation
What just happened?
Unnecessary allocation
Range-based for and Qt foreach macro
What just happened?
Data storage
Files and devices
Traversing directories
Reading and writing files
Devices
Time for action – Implementing a device to encrypt data
What just happened?
Have a go hero – A GUI for the Caesar cipher
Text streams
Binary streams
Time for action – Serialization of a custom structure
What just happened?
XML streams
Time for action – Implementing an XML parser for player data
What just happened?
What just happened?
Have a go hero – An XML serializer for player data
QVariant
QSettings
Settings hierarchy
Customizing the settings location and format
JSON files
Time for action – The player data JSON serializer
Time for action – Implementing a JSON parser
What just happened?
Pop quiz
Summary
Networking
QNetworkAccessManager
Setting up a local HTTP server
Preparing a URL for testing
Time for action – Downloading a file
Have a go hero – Extending the basic file downloader
Single network manager per application
Time for action – Displaying a proper error message
Downloading files over FTP
Downloading files in parallel
The finished signal
Time for action – Writing the OOP conform code using QSignalMapper
What just happened?
The error signal
The readyRead signal
Time for action – Showing the download progress
What just happened?
Using a proxy
Connecting to Google, Facebook, Twitter, and co.
Time for action – Using Google's Distance Matrix API
Time for action – Constructing the query
Time for action – Parsing the server's reply
Have a go hero – Choosing XML as the reply's format
Controlling the connectivity state
QNetworkConfigurationManager
QNetworkConfiguration
QNetworkSession
QNetworkInterface
Communicating between games
Time for action – Realizing a simple chat program
The server – QTcpServer
Time for action – Setting up the server
What just happened?
Time for action – Reacting on a new pending connection
What just happened?
Time for action – Forwarding a new message
Have a go hero – Using QSignalMapper
Time for action – Detecting a disconnect
What just happened?
The client
Time for action – Setting up the client
What just happened?
Time for action – Receiving text messages
Time for action – Sending text messages
Have a go hero – Extending the chat server and client
Synchronous network operations
Using UDP
Time for action – Sending a text via UDP
Have a go hero – Connecting players of the Benjamin game
Pop quiz
Summary
Custom Widgets
Raster and vector graphics
Raster painting
Painter attributes
Coordinate systems
Drawing operations
Creating a custom widget
Time for action – Custom-painted widgets
What just happened?
Time for action – Transforming the viewport
What just happened?
Time for action – Drawing an oscillogram
Time for action – Making oscillograms selectable
Have a go hero – Reacting only to the left mouse button
Touch events
Working with images
Loading
Modifying
Painting
Painting text
Static text
Optimizing widget painting
Time for action – Optimizing oscillogram drawing
What just happened?
Have a go hero – Caching the oscillogram in a pixmap
Implementing a chess game
Time for action – Developing the game architecture
What just happened?
Time for action – Implementing the game board class
What just happened?
Time for action – Understanding the ChessView class
What just happened?
Time for action – Rendering the pieces
What just happened?
Time for action – Making the chess game interactive
What just happened?
Time for action – Connecting the game algorithm
What just happened?
Have a go hero – Implementing the UI around the chess board
Have a go hero – Connecting a UCI-compliant chess engine
Pop quiz
Summary
OpenGL and Vulkan in Qt applications
Introduction to OpenGL with Qt
OpenGL windows and contexts
Accessing OpenGL functions
Using OpenGL in immediate mode
Time for action – Drawing a triangle using Qt and OpenGL
Multisampling
Time for action – Scene-based rendering
What just happened?
Time for action – Drawing a textured cube
Have a go hero – Animating a cube
Modern OpenGL with Qt
Shaders
Time for action – Shaded objects
GL buffers
Using multiple OpenGL versions
Offscreen rendering
Vulkan in Qt applications
Preparing the developing environment
Vulkan instance, window, and renderer
Time for action – Creating the minimal Vulkan project
What just happened?
Using Vulkan types and functions
Time for action – Drawing with a dynamic background color
Logs and validation
Combining OpenGL or Vulkan with Qt Widgets
Pop quiz
Summary
Scripting
Why script?
Evaluating JavaScript expressions
Time for action – Creating a JavaScript editor
What just happened?
Global object state
Exposing C++ objects and functions to JavaScript code
Accessing C++ object's properties and methods
Data type conversions between C++ and JavaScript
Accessing signals and slots in scripts
Time for action – Using a button from JavaScript
Restricting access to C++ classes from JavaScript
Creating C++ objects from JavaScript
Exposing C++ functions to JavaScript
Creating a JavaScript scripting game
Time for action – Implementing the game engine
Time for action – Exposing the game state to the JS engine
What just happened?
Time for action – Loading scripts provided by users
Time for action – Executing the strategy scripts
Time for action – Writing a strategy script
Have a go hero – Extending the game
Python scripting
Time for action – Writing a Qt wrapper for embedding Python
What just happened?
Time for action – Converting data between C++ and Python
What just happened?
Have a go hero – Implementing the remaining conversions
Time for action – Calling functions and returning values
What just happened?
Have a go hero – Wrapping Qt objects into Python objects
Pop quiz
Summary
Introduction to Qt Quick
Declarative UI programming
Time for action – Creating the first project
Time for action – Editing QML
What just happened?
Property groups
Anchors
Time for action – Positioning items relative to each other
QML types, components, and documents
How does it work?
Time for action – Property binding
A limitation of automatic property updates
Overview of QML types provided by Qt
Qt Quick Designer
Time for action – Adding a form to the project
Form editor files
Form editor interface
Time for action – Adding an import
Time for action – Adding items to the form
Time for action – Editing anchors
Time for action – Applying layouts to the items
Time for action – Assigning an expression to the property
Time for action – Exposing items as properties
What just happened?
Time for action – Creating an event handler
Qt Quick and C++
Accessing C++ objects from QML
Accessing QML objects from C++
Bringing life into static user interfaces
Fluid user interfaces
States and transitions
Time for action – Adding states to the form
Time for action – Adding smooth transition effect
What just happened?
Have a go hero – Adding an animation of the item's position
Pop quiz
Summary
Customization in Qt Quick
Creating a custom QML component
Time for action – Creating a button component
What just happened?
Time for action – Adding button content
What just happened?
Time for action – Sizing the button properly
What just happened?
Time for action – Making the button a reusable component
What just happened?
Importing components
QML and virtual resource paths
Event handlers
Time for action – Making the button clickable
What just happened?
Time for action – Visualizing button states
What just happened?
Time for action – Notifying the environment about button states
What just happened?
Touch input
Time for action – Dragging an item around
What just happened?
Time for action – Rotating and scaling a picture by pinching
What just happened?
Have a go hero – Rotating and scaling with a mouse
Keyboard input
Have a go hero – Practicing key-event propagation
Text input fields
Gamepad input
What just happened?
Sensor input
Detecting device location
Creating advanced QML components
Time for action – A simple analog clock application
What just happened?
Time for action – Adding needles to the clock
What just happened?
Time for action – Making the clock functional
What just happened?
Dynamic and lazy loading of QML objects
Creating objects on request
Delaying item creation
Imperative painting on Canvas using JavaScript
Time for action – Preparing Canvas for heartbeat visualization
What just happened?
Time for action - drawing a heartbeat
What just happened?
Time for action – Hiding properties
Time for action – Making the diagram more colorful
What just happened?
Using C++ classes as QML components
Time for action – Self-updating car dashboard
What just happened?
Time for action – Grouping engine properties
What just happened?
Time for action – Registering C++ class as QML type
Time for action – Making CarInfo instantiable from QML
What just happened?
Pop quiz
Summary
Animations in Qt Quick Games
Animation framework in Qt Quick
Generic animations
Time for action – Scene for an action game
What just happened?
Time for action – Animating the sun's horizontal movement
What just happened?
Composing animations
Time for action – Making the sun rise and set
What just happened?
Non-linear animations
Time for action – Improving the path of the sun
What just happened?
Property value sources
Time for action – Adjusting the sun's color
What just happened?
Time for action – Furnishing sun animation
What just happened?
Have a go hero – Animating the sun's rays
Behaviors
Time for action – Animating the car dashboard
What just happened?
States
Transitions
More animation types
Quick game programming
Game loops
Input processing
Time for action – Character navigation
What just happened?
Time for action – Another approach to character navigation
What just happened?
Have a go hero – Polishing the animation
Time for action – Generating coins
What just happened?
Sprite animation
Time for action – Implementing simple character animation
What just happened?
Time for action – Animating characters using sprites
What just happened?
Time for action – Adding jumping with sprite transitions
What just happened?
Have a go hero – Making Benjamin wiggle his tail in anticipation
Time for action – Revisiting parallax scrolling
What just happened?
Have a go hero – Vertical parallax sliding
Collision detection
Time for action – Collecting coins
What just happened?
Have a go hero – Extending the game
Pop quiz
Summary
Advanced Visual Effects in Qt Quick
Making the game more attractive
Auto-scaling user interfaces
Graphical effects
Have a go hero – The blur parallax scrolled game view
Particle systems
Tuning the emitter
Rendering particles
Making particles move
Time for action – Vanishing coins spawning particles
What just happened?
Custom OpenGL-based Qt Quick items
The scene graph
Time for action – Creating a regular polygon item
What just happened?
Have a go hero – Creating a supporting border for RegularPolygon
Using QPainter interface in Qt Quick
Time for action – Creating an item for drawing outlined text
What just happened?
Pop quiz
Summary
3D Graphics with Qt
Qt 3D overview
Entities and components
Qt 3D modules
Stable modules
Experimental modules
Using modules
Rendering 3D objects
Mesh, material, and transform
Lighting
Time for action – creating a 3D scene
What just happened?
Time for action – constructing the Tower of Hanoi scene
Time for action – repeating 3D objects
What just happened?
Time for action – creating disks
Handling user input
Devices
Keyboard and mouse buttons
Input chords
Analog (axis) input
Object picker
Frame-based input handling
Time for action – receiving mouse input
What just happened?
Performing animations
Time for action – animating disk movements
What just happened?
Time for action – implementing game logic
Have a go hero – improving the game
Integration with 3D modeling software
Time for action – using OBJ files for the disks
Loading a 3D scene
Working with Qt 3D using C++
Time for action – creating a 3D scene using C++
Integration with Qt Widgets and Qt Quick
Embedding Qt Quick UI into a 3D scene
Embedding a Qt 3D scene into a Qt Quick form
Pop quiz
Summary
Pop quiz answers
Other Books You May Enjoy
Leave a review - let other readers know what you think
As a leading cross-platform toolkit for all significant desktop, mobile, and embedded platforms, Qt is becoming more popular by the day. This book will help you learn the nitty-gritty of Qt and will equip you with the necessary toolsets to build apps and games. This book is designed as a beginner's guide to take programmers new to Qt from the basics, such as objects, core classes, widgets, and new features in version 5.9, to a level where they can create a custom application with the best practices of programming with Qt.
From a brief introduction of how to create an application and prepare a working environment for both desktop and mobile platforms, we will dive deeper into the basics of creating graphical interfaces and Qt's core concepts of data processing and display. As you progress through the chapters, you'll learn to enrich your games by implementing network connectivity and employing scripting. Delve into Qt Quick, OpenGL, and various other tools to add game logic, design animation, add game physics, handle gamepad input, and build astonishing UIs for games. Toward the end of this book, you'll learn to exploit mobile device features, such as sensors and geolocation services, to build engaging user experiences.
This book will be interesting and helpful to programmers and application and UI developers who have basic knowledge of C++. Additionally, some parts of Qt allow you to use JavaScript, so basic knowledge of this language will also be helpful. No previous experience with Qt is required. Developers with up to a year of Qt experience will also benefit from the topics covered inthis book.
Chapter 1, Introduction to Qt, familiarizes you with the standard behavior that is required when creating cross-platform applications and shows you a bit of history of Qt and how it evolved over time with an emphasis on the most recent architectural changes in Qt.
Chapter 2, Installation, guides you through the process of installing a Qt binary release for desktop platforms, setting up the bundled IDE, and looks at various configuration options related to cross-platform programming.
Chapter 3, Qt GUI Programming, shows you how to create classic user interfaces with the Qt Widgets module. It also familiarizes you with the process of compiling applications using Qt.
Chapter 4, Custom 2D Graphics with Graphics View, familiarizes you with 2D object-oriented graphics in Qt. You will learn how to use built-in items to compose the final results as well as create your own items supplementing what is already available.
Chapter 5, Animations in Graphics View, describes the Qt Animation framework, the property system, and shows you how to implement animations in Graphics View. It will guide you through the process of creating a game featuring 2D graphics and animations.
Chapter 6, Qt Core Essentials, covers the concepts related to data processing and display in Qt—file handling in different formats, Unicode text handling and displaying user-visible strings in different languages, and regular expression matching.
Chapter 7, Networking, demonstrates the IP networking technologies that are available in Qt. It will teach you how to connect to TCP servers, implement a TCP server, and implement fast communication via UDP.
Chapter 8, Custom Widgets, describes the whole mechanism related to 2D software rendering in Qt, and teaches you how to create your own widget classes with unique functionalities.
Chapter 9, OpenGL and Vulkan in Qt applications, discusses Qt capabilities related to accelerated 3D graphics. You will learn how to perform fast 3D drawing using OpenGL and Vulkan APIs and use the convenient wrappers Qt provides for them.
Chapter 10, Scripting, covers the benefits of scripting in applications. It will teach you how to employ a scripting engine for a game by using JavaScript or Python.
Chapter 11, Introduction to Qt Quick, teaches you how to program resolution-independent fluid user interfaces using a QML declarative engine and Qt Quick scene graph environment.
Chapter 12, Customization in Qt Quick, focuses on how to implement new graphical items in Qt Quick and implement custom event handling.
Chapter 13, Animations in Qt Quick Games, familiarizes you with the ways to perform animations in Qt Quick and give more hints for implementing games in Qt Quick.
Chapter 14, Advanced Visual Effects in Qt Quick, goes through some advanced concepts that will allow you to perform truly unique graphical effects in Qt Quick.
Chapter 15, 3D Graphics with Qt, outlines using Qt's high-level API for 3D graphics and show you how to implement an animated 3D game.
Chapter 16, Miscellaneous and Advanced Concepts, demonstrates the important aspects of Qt programming that didn't make it into the other chapters but may be important for game programming. This chapter is available online at https://www.packtpub.com/sites/default/files/downloads/MiscellaneousandAdvancedConcepts.pdf.
You don't need to own or install any particular software before starting to work with the book. A common Windows, Linux, or MacOS system should be sufficient. Chapter 2, Installation, contains detailed instructions on how to download and set up everything you'll need.
In this book, you will find several headings that appear frequently:
The
Time for action
section
contains clear instructions on how to complete a procedure or task.
The
What just happened?
section explains the working of the tasks or instructions that you have just completed.
The
Have a go hero
sections contain practical challenges that give you ideas to experiment with what you have learned.
The
Pop quiz
sections contain short single-choice questions intended to help you test your own understanding. You will find the answers at the end of the book.
While going through the chapters, you will be presented with multiple games and other projects as well as detailed descriptions of how to create them. We advise you to try to create these projects yourself using the instructions we'll give you. If at any point of time you have trouble following the instructions or don't know how to do a certain step, you should take a pick at the example code files to see how it can be done. However, the most important and exciting part of learning is to decide what you want to implement and then find a way to do it, so pay attention to the "Have a go hero" sections or think of your own way to improve each project.
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/Game-Programming-Using-Qt-5-Beginners-Guide-Second-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
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.
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.
In this chapter, you will learn what Qt is and how it evolved. We will describe the structure of the Qt framework and the differences between its versions. Finally, you will learn how to decide which Qt licensing scheme is right for your projects.
The main topics covered in this chapter are:
Qt history
Supported platforms
Structure of the Qt framework
Qt versions
Qt licenses
The development of Qt started in 1991 by two Norwegians—Eirik Chambe-Eng and Haavard Nord—who were looking to create a cross-platform GUI programming toolkit. The first commercial client of Trolltech (the company that created the Qt toolkit) was the European Space Agency. The commercial use of Qt helped Trolltech sustain further development. At that time, Qt was available for two platforms—Unix/X11 and Windows—however, developing with Qt for Windows required buying a proprietary license, which was a significant drawback in porting the existing Unix/Qt applications.
A major step forward was the release of Qt Version 3.0 in 2001, which saw the initial support for Mac as well as an option to use Qt for Unix and Mac under a liberal GPL license. Still, Qt for Windows was only available under a paid license. Nevertheless, at that time, Qt had support for all the important players in the market—Windows, Mac, and Unix desktops, with Trolltech's mainstream product and Qt for embedded Linux.
In 2005, Qt 4.0 was released, which was a real breakthrough for a number of reasons. First, the Qt API was completely redesigned, which made it cleaner and more coherent. Unfortunately, at the same time, it made the existing Qt-based code incompatible with 4.0, and many applications needed to be rewritten from scratch or required much effort to be adapted to the new API. It was a difficult decision, but from the time perspective, we can see it was worth it. Difficulties caused by changes in the API were well countered by the fact that Qt for Windows was finally released under GPL. Many optimizations were introduced that made Qt significantly faster. Lastly, Qt, which was a single library until now, was divided into a number of modules. This allowed programmers to only link to the functionality that they used in their applications, reducing the memory footprint and the dependencies of their software.
In 2008, Trolltech was sold to Nokia, which at that time was looking for a software framework to help it expand and replace its Symbian platform in the future. The Qt community became divided; some people were thrilled, others were worried after seeing Qt's development get transferred to Nokia. Either way, new funds were pumped into Qt, speeding up its progress and opening it for mobile platforms—Symbian and then Maemo and MeeGo.
For Nokia, Qt was not considered a product of its own, but rather a tool. Therefore, Nokia decided to introduce Qt to more developers by adding a very liberal Lesser General Public License (LGPL) that allowed the usage of the framework for both open and closed source development.
Bringing Qt to new platforms and less powerful hardware required a new approach to create user interfaces and to make them more lightweight, fluid, and attractive. Nokia engineers working on Qt came up with a new declarative language to develop such interfaces—the Qt Modeling Language (QML) and a Qt runtime for it called Qt Quick.
The latter became the primary focus of the further development of Qt, practically stalling all non-mobile-related work, channeling all efforts to make Qt Quick faster, easier, and more widespread. Qt 4 was already in the market for seven years, and it became obvious that another major version of Qt had to be released. It was decided to bring more engineers to Qt by allowing anyone to contribute to the project. The Qt Project founded by Nokia in 2011 provided an infrastructure for code review and introduced an open governance model, allowing outside developers to participate in decision making.
Nokia did not manage to finish working on Qt 5.0. As a result of an unexpected turnover of Nokia toward different technology in 2011, the Qt division was sold in mid 2012 to the Finnish company Digia that managed to complete the effort and release Qt 5.0, a completely restructured framework, in December of the same year. While Qt 5.0 introduced a lot of new features, it was mostly compatible with Qt 4 and allowed developers to seamlessly migrate to the new major version.
In 2014, Digia formed the Qt Company that is now responsible for Qt development, commercialization, and licensing. All Qt-related web resources scattered across Qt Project and Digia websites were eventually unified at https://www.qt.io/. Qt continues to receive bug fixes, new features, and new platform support. This book is based on Qt 5.9, which was released in 2017.
Qt is an application-programming framework that is used to develop cross-platform applications. What this means is that software written for one platform can be ported and executed on another platform with little or no effort. This is obtained by limiting the application source code to a set of calls to routines and libraries available to all the supported platforms, and by delegating all tasks that may differ between platforms (such as drawing on the screen and accessing system data or hardware) to Qt. This effectively creates a layered environment (as shown in the following diagram), where Qt hides all platform-dependent aspects from the application code:
Of course, at times, we need to use some functionality that Qt doesn't provide. In such situations, it is important to use a conditional compilation for platform-specific code. Qt provides a wide set of macros specifying the current platform. We will return to this topic in Chapter 6, Qt Core Essentials.
The framework is available for a number of platforms, ranging from classical desktop environments through embedded systems to mobile devices. Qt 5.9 supports the following platforms:
Desktop platforms: Windows, Linux, and macOS
Mobile platforms: UWP
, Android
, and iOS
Embedded platforms: VxWorks, INTEGRITY, QNX, and Embedded Linux
It is likely that the list of supported platforms will change in future Qt versions. You should refer to the Supported Platforms documentation page for your Qt version for detailed information about supported versions of operating systems and compilers.
For the most part of the history of desktop application development, specifying sizes of GUI elements in pixels was the common practice. While most operating systems had dots per inch (DPI) settings and APIs for taking it into account for a long time, the majority of existing displays had approximately the same DPI, so applications without high DPI support were common.
The situation changed when high-DPI displays became more common in the market—most notably in mobile phones and tablets, but also in laptops and desktops. Now, even if you only target desktop platforms, you should think about supporting different DPI settings. When you target mobile devices, this becomes mandatory.
If you are using Qt Widgets or Qt Quick, you often don't need to specify pixel sizes at all. Standard widgets and controls will use fonts, margins, and offsets defined by the style. If layouts are used, Qt will determine positions and sizes of all GUI items automatically. Avoid specifying constant sizes for GUI elements when possible. You may use sizes related to sizes of other GUI elements, the window, or the screen. Qt also provides an API for querying screen DPI, GUI style metrics, and font metrics, which should help to determine the optimal size for the current device.
On macOS and iOS, Qt Widgets and Qt Quick applications are scaled automatically using a virtual coordinate system. Pixel values in the application remain the same, but the GUI will scale according to the DPI of the current display. For example, if the pixel ratio is set to 2 (a common value for retina displays), creating a widget with 100 "pixels" width will produce a widget with 200 physical pixels. That means that the application doesn't have to be highly aware of DPI variations. However, this scaling does not apply to OpenGL, which always uses physical pixels.
Each Qt version number (for example, 5.9.2) consists of major, minor, and patch components. Qt pays special attention to forwards and backwards compatibility between different versions. Small changes which are both forwards and backwards compatible (typically bug fixes without changing any API) are indicated by changing only the patch version. New minor versions usually bring in new API and features, so they are not forwards compatible. However, all minor versions are backwards binary and source compatible. This means that if you're transitioning to a newer minor version (for example, from 5.8 to 5.9), you should always be able to rebuild your project without changes. You can even transition to a new minor version without rebuilding, by only updating shared Qt libraries (or letting the package manager of the OS do that). Major releases indicate big changes and may break backwards compatibility. However, the latest major release (5.0) was mostly source compatible with the previous version.
Qt declares Long Term Support (LTS) for certain versions. LTS versions receive patch-level releases with bug fixes and security fixes for three years. Commercial support is available for even longer periods. Current LTS releases at the time of writing are 5.6 and 5.9.
As Qt expanded over time, its structure evolved. At first, it was just a single library, then a set of libraries. When it became harder to maintain and update for the growing number of platforms that it supported, a decision was made to split the framework into much smaller modules contained in two module groups—Qt Essentials and Qt Add-ons. A major decision relating to the split was that each module could now have its own independent release schedule.
The Essentials group contains modules that are mandatory to implement for every supported platform. This implies that if you are implementing your system using modules from this group only, you can be sure that it can be easily ported to any other platform that Qt supports. The most important relations between Qt Essentials modules are shown in the following diagram:
Some of the modules are explained as follows:
The
Qt Core
module contains the most basic Qt functionality that all other modules rely on. It provides support for event processing, meta-objects, data I/O, text processing, and threading. It also brings a number of frameworks, such as the Animation framework, the State Machine framework, and the Plugin framework.
The
Qt GUI
module provides basic cross-platform support to build user interfaces. It contains the common functionality required by more high-level GUI modules (Qt Widgets and Qt Quick). Qt GUI contains classes that are used to manipulate windows that can be rendered using either the raster engine or OpenGL. Qt supports desktop OpenGL as well as OpenGL ES 1.1 and 2.0.
Qt Widgets
extends the GUI module with the ability to create a user interface using widgets, such as buttons, edit boxes, labels, data views, dialog boxes, menus, and toolbars, which are arranged using a special layout engine. Qt Widgets utilizes Qt's event system to handle input events in a cross-platform way. This module also contains the implementation of an object-oriented 2D graphics canvas called Graphics View.
Qt Quick
is an extension of Qt GUI, which provides a means to create lightweight fluid user interfaces using QML. It is described in more detail later in this chapter, as well as in
Chapter 11
, Introduction to Qt Quick
.
Qt QML
is an implementation of the QML language used in Qt Quick. It also provides API to integrate custom C++ types into QML's JavaScript engine and to integrate QML code with C++.
Qt Network
brings support for IPv4 and IPv6 networking using TCP and UDP. It also contains HTTP, HTTPS, FTP clients, and it extends support for DNS lookups.
Qt Multimedia
allows programmers to access audio and video hardware (including cameras and FM radio) to record and play multimedia content. It also features 3D positional audio support.
Qt SQL
brings a framework that is used to manipulate SQL databases in an abstract way.
This group contains modules that are optional for any platform. This means that if a particular functionality is not available on some platform or there is nobody willing to spend time working on this functionality for a platform, it will not prevent Qt from supporting this platform. We'll mention some of the most important modules here:
Qt Concurrent
: This handles multi-threaded processing
Qt 3D
: This provides high-level OpenGL building blocks
Qt Gamepad
: This enables applications to support gamepad hardware
Qt D-Bus
: This allows your application to communicate with others via the D-Bus mechanism
Qt XML Patterns
: This helps us to access XML data
Many other modules are also available, but we will not cover them here.
Some Qt features require additional build steps during the compilation and linking of the project. For example, Meta-Object Compiler (moc), User Interface Compiler (uic), and Resource Compiler (rcc) may need to be executed to handle Qt's C++ extensions and features. For convenience, Qt provides the qmake executable that manages your Qt project and generates files required for building it on the current platform (such as Makefile for the make utility). qmake reads the project's configuration from a project file with the .pro extension. Qt Creator (the IDE that comes with Qt) automatically creates and updates that file, but it can be edited manually to alter the build process.
Alternatively, CMake can be used to organize and build the project. Qt provides CMake plugins for performing all the necessary build actions. Qt Creator also has fairly good support for CMake projects. CMake is more advanced and powerful than qmake, but it's probably not needed for projects with a simple build process.
You can use modern C++ in your Qt projects. Qt's build tool (qmake) allows you to specify the C++ standard you want to target. Qt itself introduces an improved and extended API by using new C++ features when possible. For example, it uses ref-qualified member functions and introduces methods accepting initializer lists and rvalue references. It also introduces new macros that help you deal with compilers that may or may not support new standards.
If you use a recent C++ revision, you have to pay attention to the compiler versions you use across the target platforms because older compilers may not support the new standard. In this book, we will assume C++11 support, as it is widely available already. Thus, we'll use C++11 features in our code, such as range-based for loops, scoped enumerations, and lambda expressions.
Qt is available under two different licensing schemes—you can choose between a commercial license and an open source one. We will discuss both here to make it easier for you to choose. If you have any doubts regarding whether a particular licensing scheme applies to your use case, you better consult a professional lawyer.
The advantage of open source licenses is that we don't have to pay anyone to use Qt; however, the downside is that there are some limitations imposed on how it can be used.
When choosing the open source edition, we have to choose between GPL 3.0 and LGPL 3. Since LGPL is more liberal, in this chapter we will focus on it. Choosing LGPL allows you to use Qt to implement systems that are either open source or closed source—you don't have to reveal the sources of your application to anyone if you don't want to.
However, there are a number of restrictions you need to be aware of:
Any modifications that you make to Qt itself need to be made public, for example, by distributing source code patches alongside your application binary.
LGPL requires that users of your application must be able to replace Qt libraries that you provide them with other libraries with the same functionality (for example, a different version of Qt). This usually means that you have to dynamically link your application against Qt so that the user can simply replace Qt libraries with his own. You should be aware that such substitutions can decrease the security of your system; thus, if you need it to be very secure, open source may not be the option for you.
LGPL is incompatible with a number of licenses, especially proprietary ones, so it is possible that you won't be able to use Qt with some commercial components.
Some Qt modules may have different licensing restrictions. For example, Qt Charts, Qt Data Visualization, and Qt Virtual Keyboard modules are not available under LGPL and can only be used under GPL or the commercial license.
The open source edition of Qt can be downloaded directly from https://www.qt.io.
Most of the restrictions are lifted if you decide to buy a commercial license for Qt. This allows you to keep the entire source code a secret, including any changes you may want to incorporate into Qt. You can freely link your application statically against Qt, which means fewer dependencies, a smaller deployment bundle size, and a faster startup. It also increases the security of your application, as end users cannot inject their own code into the application by replacing a dynamically loaded library with their own.
In this chapter, you learned about the architecture of Qt. We saw how it evolved over time and we had a brief overview of what it looks like now. Qt is a complex framework and we will not manage to cover it all, as some parts of its functionality are more important for game programming than others that you can learn on your own in case you ever need them. Now that you know what Qt is, we can proceed with the next chapter, where you will learn how to install Qt on to your development machine.
In this chapter, you will learn how to install Qt on your development machine, including Qt Creator, an IDE tailored to use with Qt. You will see how to configure the IDE for your needs and learn the basic skills to use that environment. By the end of this chapter, you will be able to prepare your working environment for both desktop and embedded platforms using the tools included in the Qt release.
The main topics covered in this chapter are as follows:
Installing Qt and its developer tools
Main controls of Qt Creator
Qt documentation
Before you can start using Qt on your machine, it needs to be downloaded and installed. Qt can be installed using dedicated installers that come in two flavors: the online installer, which downloads all the needed components on the fly, and a much larger offline installer, which already contains all the required components. Using an online installer is easier for regular desktop installs, so we prefer this approach.
All Qt resources, including the installers, are available at https://qt.io. To obtain the open source version of Qt, go to https://www.qt.io/download-open-source/. The page suggests the online installer for your current operating system by default, as shown in the following screenshot. Click on the Download Now button to download the online installer, or click on View All Downloads to select a different download option:
When the download is complete run the installer, as shown:
Click on Next to begin the installation process. If you are using a proxy server, click on Settings and adjust your proxy configuration. Then, either log into your Qt Account or click on Skip, if you don't have one.
Click on Next again, and after a while of waiting as the downloader checks remote repositories, you'll be asked for the installation path. Ensure that you choose a path where you have write access and enough free space. It's best to put Qt into your personal directory, unless you ran the installer as the system administrator user. Clicking on Next again will present you with the choice of components that you wish to install, as shown in the following screenshot. You will be given different choices depending on your platform:
Before we continue, you need to choose which Qt version you want to install. We recommend that you use the most recent stable version, that is, the first item under the Qt section. Ignore the Preview section, as it contains prerelease packages that may be unstable. If you want to be fully consistent with the book, you can choose Qt 5.9.0, but it's not required. The installer also allows you to install multiple Qt versions at once.
Expand the section corresponding to the Qt version you want to install, and choose whichever platforms you need. Select at least one desktop platform to be able to build and run desktop applications. When in Windows, you have to make additional choices for the desktop builds. Select the 32-bit or 64-bit version and choose the compiler you want to be working with. If you have a Microsoft C++ compiler (provided with Visual Studio or Visual C++ Build Tools), you can select the build corresponding to the installed MSVC version. If you don't have a Microsoft compiler or you simply don't want to use it, choose the MinGW build and select the corresponding MinGW version in the Tools section of the package tree.
If you want to build Android applications, choose the option corresponding to the desired Android platform. In Windows, you can select a UWP build to create Universal Windows Platform applications.
The installer will always install Qt Creator—the IDE (integrated development environment) optimized for creating Qt applications. You may also select Qt add-ons that you want to use.
After choosing the required components and clicking on Next again, you will have to accept the licensing terms for Qt by marking an appropriate choice, as shown in the following screenshot:
After you click on Install, the installer will begin downloading and installing the required packages. Once this is done, your Qt installation will be ready. At the end of the process, you will be given an option to launch Qt Creator:
The process we went through results in the whole Qt infrastructure appearing on your disk. You can examine the directory you pointed to the installer to see that it created a number of subdirectories in this directory, one for each version of Qt chosen with the installer, and another one called Tools that contains Qt Creator. The Qt directory also contains a MaintenanceTool
