Game Programming Using Qt: Beginner's Guide
By Wysota Witold and Haas Lorenz
()
About this ebook
A complete guide to designing and building fun games with Qt and Qt Quick 2 using associated toolsets
About This Book- Learn to create simple 2D to complex 3D graphics and games using all possible tools and widgets available for game development in Qt
- Understand technologies such as QML, Qt Quick, OpenGL, and Qt Creator, and learn the best practices to use them to design games
- Learn Qt with the help of many sample games introduced step-by-step in each chapter
If you want to create great graphical user interfaces and astonishing games with Qt, this book is ideal for you. Any previous knowledge of Qt is not required, however knowledge of C++ is mandatory.
What You Will Learn- Install Qt on your system
- Understand the basic concepts of every Qt game and application
- Develop 2D object-oriented graphics using Qt Graphics View
- Build multiplayer games or add a chat function to your games with Qt's Network module
- Script your game with Qt Script
- Program resolution-independent and fluid UI using QML and Qt Quick
- Control your game flow as per the sensors of a mobile device
- See how to test and debug your game easily with Qt Creator and Qt Test
Qt is the leading cross-platform toolkit for all significant desktop, mobile, and embedded platforms and is becoming more popular by the day, especially on mobile and embedded devices. Despite its simplicity, it's a powerful tool that perfectly fits game developers' needs. Using Qt and Qt Quick, it is easy to build fun games or shiny user interfaces. You only need to create your game once and deploy it on all major platforms like iOS, Android, and WinRT without changing a single source file.
The book begins with a brief introduction to creating an application and preparing a working environment for both desktop and mobile platforms. It then dives deeper into the basics of creating graphical interfaces and Qt core concepts of data processing and display before you try creating a game. As you progress through the chapters, you'll learn to enrich your games by implementing network connectivity and employing scripting. We then delve into Qt Quick, OpenGL, and various other tools to add game logic, design animation, add game physics, and build astonishing UI for the games. Towards the final chapters, you'll learn to exploit mobile device features such as accelerators and sensors to build engaging user experiences. If you are planning to learn about Qt and its associated toolsets to build apps and games, this book is a must have.
Style and approachThis is an easy-to-follow, example-based, comprehensive introduction to all the major features in Qt. The content of each chapter is explained and organized around one or multiple simple game examples to learn Qt in a fun way.
Related to Game Programming Using Qt
Related ebooks
Game Programming Using Qt: Beginner's Guide Rating: 0 out of 5 stars0 ratingsOpenSceneGraph 3.0 Beginner's Guide Rating: 0 out of 5 stars0 ratingsCorona SDK Mobile Game Development: Beginner's Guide - Second Edition Rating: 0 out of 5 stars0 ratingsCorona SDK Mobile Game Development Beginner's Guide Rating: 5 out of 5 stars5/53D Game Development with Microsoft Silverlight 3: Beginner's Guide Rating: 0 out of 5 stars0 ratingsMonkey Game Development: Beginner's Guide Rating: 0 out of 5 stars0 ratingsHTML5 Game Development by Example: Beginner's Guide - Second Edition Rating: 1 out of 5 stars1/5Sparrow iOS Game Framework Beginner’s Guide Rating: 0 out of 5 stars0 ratingsjQuery 2.0 Animation Techniques Beginner's Guide Rating: 0 out of 5 stars0 ratingsLearning iPhone Game Development with Cocos2D 3.0 Rating: 0 out of 5 stars0 ratingsCeltx: Open Source Screenwriting Beginner's Guide Rating: 5 out of 5 stars5/5Unity 3.x Game Development by Example Beginner's Guide Rating: 3 out of 5 stars3/5Unreal Development Kit Game Programming with UnrealScript: Create games beyond your imagination with the Unreal Development Kit Rating: 0 out of 5 stars0 ratingsMac Application Development by Example: Beginner's Guide Rating: 0 out of 5 stars0 ratingsGeoServer Beginner's Guide Rating: 0 out of 5 stars0 ratingsOUYA Game Development by Example Rating: 0 out of 5 stars0 ratingsVaadin 7 UI Design By Example: Beginners Guide Rating: 0 out of 5 stars0 ratingsPanda3D 1.6 Game Engine Beginner's Guide Rating: 0 out of 5 stars0 ratingsCocos2d-x by Example: Beginner's Guide - Second Edition Rating: 0 out of 5 stars0 ratingsHTML5 Web Application Development By Example: Learn how to write rich, interactive web applications using HTML5 and CSS3 through real-world examples. In a world of proliferating platforms and devices, being able to create your own ‚Äúgo-anywhere‚Äù applications gives you a significant advantage. Rating: 0 out of 5 stars0 ratingsInkscape Beginner’s Guide Rating: 5 out of 5 stars5/5C# 2008 and 2005 Threaded Programming: Beginner's Guide Rating: 0 out of 5 stars0 ratingshaXe 2 Beginner's Guide Rating: 0 out of 5 stars0 ratingsUnity Android Game Development by Example Beginner's Guide Rating: 4 out of 5 stars4/5LiveCode Mobile Development: Beginner's Guide - Second Edition Rating: 4 out of 5 stars4/5Unity 4.x Game Development by Example Beginner's Guide Rating: 3 out of 5 stars3/5Oracle ADF 11gR2 Development Beginner's Guide Rating: 0 out of 5 stars0 ratingsXNA 4 3D Game Development by Example: Beginner's Guide Rating: 0 out of 5 stars0 ratingsGNU Octave Beginner's Guide Rating: 3 out of 5 stars3/5
Programming For You
Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Unreal Engine from Zero to Proficiency (Foundations): Unreal Engine from Zero to Proficiency, #1 Rating: 3 out of 5 stars3/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsLinux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5
Reviews for Game Programming Using Qt
0 ratings0 reviews
Book preview
Game Programming Using Qt - Wysota Witold
Table of Contents
Game Programming Using Qt
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Time for action – heading
What just happened?
Pop quiz – heading
Have a go hero – heading
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Introduction to Qt
The cross-platform programming
What just happened?
Qt Platform Abstraction
Supported platforms
A journey through time
New in Qt 5
Restructured codebase
Qt Essentials
Qt Add-ons
Qt Quick 2.0
Meta-objects
C++11 support
Choosing the right license
An open source license
A commercial license
Summary
2. Installation
Installing the Qt SDK
Time for action – installing Qt using an online installer
What just happened?
Setting up Qt Creator
Time for action – loading an example project
What just happened?
Time for action – running the Affine Transformations project
What just happened?
Building Qt from sources
Time for action – setting up Qt sources using Git
What just happened?
Time for action – configuring and building Qt
What just happened?
Summary
3. Qt GUI Programming
Windows and dialogs
Creating a Qt project
Time for action – creating a Qt Desktop project
What just happened?
Adding child widgets to a window
Managing widget content
Time for action – implementing a tic-tac-toe game board
What just happened?
Qt meta-objects
Signals and slots
Pop quiz – making signal-slot connections
Time for action – functionality of a tic-tac-toe board
Properties
Declaring a property
Using a property
Time for action – adding properties to the board class
What just happened?
Designing GUIs
Time for action – designing the game configuration dialog
What just happened?
Time for action – polishing the dialog
Accelerators and label buddies
The tab order
Signals and slots
What just happened?
Using designer forms
Direct approach
The multiple-inheritance approach
The single inheritance approach
Time for action – the logic of the dialog
An application's main window
The Qt resource system
Time for action – the main window of the application
What just happened?
Time for action – adding a pull-down menu
What just happened?
Time for action – creating a toolbar
What just happened?
Time for action – filling in the central widget
What just happened?
Time for action – putting it all together
What just happened?
Have a go hero – extending the game
Pop quiz – using widgets
Summary
4. Qt Core Essentials
Text handling
Manipulating strings
Encoding and decoding text
Basic string operations
The string search and lookup
Dissecting strings
Converting between numbers and strings
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
Data storage
Files and devices
Traversing directories
Getting access to the basic file
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
Data serialization
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?
Have a go hero – an XML serializer for player data
JSON files
Time for action – the player data JSON serializer
Time for action – implementing a JSON parser
What just happened?
QSettings
Pop quiz – Qt core essentials
Summary
5. Graphics with Qt
Raster painting
Painter attributes
Widget painting
Time for action – custom-painted widgets
What just happened?
Time for action – transforming the viewport
What just happened?
Time for action – drawing an oscillogram
Input events
Time for action – making oscillograms selectable
Have a go hero – reacting only to the left mouse button
Working with images
Loading
Modifying
Painting
Painting text
Static text
Rich text
Optimized drawing
Time for action – optimizing oscillogram drawing
What just happened?
Have a go hero – implementing a double-buffered oscillogram
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
OpenGL
Introduction to OpenGL with Qt
Time for action – drawing a triangle using Qt and OpenGL
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
Off-screen rendering
Summary
6. Graphics View
Graphics View architecture
Items
Parent child relationship
Appearance
Time for action – creating a black, rectangular item
What just happened?
Time for action – reacting to an item's selection state
What just happened?
Time for action – making the item's size definable
What just happened?
Have a go hero – customizing the item
Standard items
Coordinate system of the items
Time for action – creating items with different origins
What just happened?
Time for action – rotating an item
What just happened?
Have a go hero – applying multiple transformations
Scenes
Adding items to the scene
Time for action – adding an item to a scene
What just happened?
Interacting with items on the scene
Rendering
Time for action – rendering the scene's content to an image
What just happened?
Have a go hero – rendering only specific parts of a scene
Coordinate system of the scene
Time for action – transforming parent items and child items
What just happened?
Have a go hero – playing with the z value
View
Time for action – putting it all together!
What just happened?
Showing specific areas of the scene
Transforming the scene
Time for action – creating an item where transformations can easily be seen
What just happened?
Time for action – implementing the ability to scale the scene
What just happened?
Time for action – implementing the ability to move the scene
What just happened?
Time for action – taking the zoom level into account
What just happened?
Questions you should keep in mind
The jumping elephant or how to animate the scene
The game play
The player item
Time for action – creating an item for Benjamin
What just happened?
The playing field
The scene
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
QObject and items
Time for action – using properties, signals, and slots with items
Property animations
Time for action – using animations to move items smoothly
What just happened?
Have a go hero – letting the scene handle Benjamin's jump
Time for action – keeping multiple animations in sync
What just happened?
Item collision detection
Time for action – making the coins explode
What just happened?
Setting up the playing field
Have a go hero – extending the game
A third way of animation
Widgets inside Graphics View
Optimization
A binary space partition tree
Caching the item's paint function
Optimizing the view
Pop quiz – mastering Graphics View
Summary
7. Networking
QNetworkAccessManager
Downloading files over HTTP
Time for action – downloading a file
Have a go hero – extending the basic file downloader
Error handling
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
The downloadProgress method
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 with a user list
Improvements
Using UDP
Time for action – sending a text via UDP
Have a go hero – connecting players of the Benjamin game
Pop quiz – test your knowledge
Summary
8. Scripting
Why script?
The basics of Qt Script
Evaluating JavaScript expressions
Time for action – creating a Qt Script editor
What just happened?
Time for action – sandboxed script evaluation
What just happened?
Integrating Qt and Qt Script
Exposing objects
Time for action – employing scripting for npc AI
What just happened?
Have a go hero – extending the Dungeons & Dragons game
Exposing functions
Exposing C++ functions to scripts
Exposing script functions to C++
Time for action – storing the script
What just happened?
Time for action – providing an initialization function
What just happened?
Time for action – implementing the heartbeat event
What just happened?
Have a go hero – defending against attacks
Using signals and slots in scripts
Have a go hero – triggering defense using signals and slots
Creating Qt objects in scripts
Error recovery and debugging
Extensions
The other Qt JavaScript environment
Alternatives to JavaScript
Python
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 – scripting
Summary
9. Qt Quick Basics
Fluid user interfaces
Declarative UI programming
Element properties
Group properties
Object hierarchies
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?
Event handlers
Mouse input
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
Using components in Qt Quick
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 objects
Using components in detail
Creating objects on request
Delaying item creation
Accessing your item's component functionality
Imperative painting
Time for action – preparing Canvas for heartbeat visualization
What just happened?
Time for action – drawing a heartbeat
What just happened?
Time for action – making the diagram more colorful
What just happened?
Qt Quick and C++
Creating QML objects from C++
Pulling QML objects to C++
Pushing C++ objects to QML
Time for action – self-updating car dashboard
What just happened?
Time for action – grouping engine properties
What just happened?
Extending QML
Registering classes as QML elements
Time for action – making CarInfo instantiable from QML
What just happened?
Custom Qt Quick items
OpenGL items
Time for action – creating a regular polygon item
What just happened?
Have a go hero – creating a supporting border for RegularPolygon
Painted items
Time for action – creating an item for drawing outlined text
What just happened?
Summary
10. Qt Quick
Bringing life into static user interfaces
Animating elements
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 and transitions
More animation types
Quick game programming
Game loops
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
Parallax scrolling
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?
Notes on collision detection
Eye candy
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?
Summary
A. Pop Quiz Answers
Chapter 3, Qt GUI Programming
Pop quiz – making signal-slot connections
Pop quiz – using widgets
Chapter 4, Qt Core Essentials
Pop quiz – Qt core essentials
Chapter 6, Graphics View
Pop quiz – mastering Graphics View
Chapter 7, Networking
Pop quiz – testing your knowledge
Chapter 8, Scripting
Pop quiz – scripting
Chapter 11, Miscellaneous and Advanced Concepts
Pop quiz – testing your knowledge
Index
Game Programming Using Qt
Game Programming Using Qt
Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: January 2016
Production Reference: 1210116
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-887-4
www.packtpub.com
Credits
Authors
Witold Wysota
Lorenz Haas
Reviewers
Simone Angeloni
Rahul De
Pooya Eimandar
Shaveen Kumar
M. Cihan Özer
Acquisition Editor
Vinay Argekar
Content Development Editor
Pooja Mhapsekar
Technical Editor
Mrunmayee Patil
Copy Editor
Neha Vyas
Project Coordinator
Sanjeet Rao
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Graphics
Disha Haria
Jason Monterio
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
About the Authors
Witold Wysota is a software architect and developer living in Poland. He started his adventure with Qt in 2004 when he joined QtForum.org and started answering questions about programming with Qt. Shortly afterwards, he became part of the moderator group of the forum. In 2006, together with the moderator team, he established QtCentre.org, which quickly became the largest community-driven support site devoted to Qt. For a number of years, he conducted commercial, academic, and public trainings and workshops and has been giving lectures on Qt, Qt Quick, and related technologies. He is a certified Qt developer and was a member of Qt Education Advisory Board with Nokia, where he helped prepare materials in order to use Qt in educational activities.
Witold was also a technical reviewer for Foundations of Qt Development, Johan Thelin, Apress Publishing, a book about Qt 4, and an author of a couple of articles on programming with Qt.
In real life, he is a passionate adept of Seven Star Praying Mantis, a traditional style of Chinese martial arts.
I would like to thank all the people who have worked on Qt's development over the years for creating such a great programming framework, which was the main force that helped me to shape my programming career.
I would also like to thank Lorenz for helping me with the book as well as the team at Packt Publishing for having a magnitude of patience for me during the process of the creation of this book.
Lorenz Haas is a passionate programmer who started his Qt career with Qt 3. Thrilled by Qt's great community, especially the one at QtCentre.org, 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 at a medium-sized IT company based in Erlangen, Germany, as a lead software architect. He mainly develops machine controls and their user interfaces as well as general solutions for the industry sector. Additionally, he runs his own small consultancy and programming business called Histomatics (http://www.histomatics.de).
A few years ago, he started contributing to Qt Creator. He added a couple of refactoring options that you probably rely on a regular basis if you use Qt Creator. He is also the author of the Beautifier plugin.
I would like to thank Witold who guided me through my first steps into the Qt world back in the days and who still assists me with any problems that arise. I am also very grateful to him for taking me on board for this book writing project. He's an excellent teacher and tutor!
Secondly, I would like to thank the team at Packt Publishing, who helped and guided us through the entire process of writing this book.
About the Reviewers
Simone Angeloni is a software developer and consultant with over a decade of experience in C++ and scripting languages. He is a passionate gamer, but an even more passionate modder and game designer.
He is currently working for Crytek GmbH and developing the UI of the free-to-play, award-winning video game Warface. Before this, he was realizing configuration systems for railway signaling and creating standalone applications with Qt. Later, he worked with universities and the National Institute of Nuclear Physics to realize fast data acquisition for particle accelerators.
Recently, he founded Clockwise Interactive, a game company that is currently working on the production of its first title.
Rahul De is a 23-year-old systems and server-side engineer from Kolkata, India. He recently graduated from the Vellore Institute of Technology with a bachelor of technology degree in computer science and now works with ThoughtWorks. Being a tech and open source enthusiast and a proper geeks geek
, Rahul took up programming at a very young age and quickly matured from developing small-time native applications for desktops to maintaining servers, writing compilers, building IDEs, and enhancing Qt. His latest pet projects involve Medusa—a JIT compiler for Python using Qt, which aims to provide up to a 1500 percent boost for Python projects.
Being an avid gamer, he has already dabbled quite a bit with various engines such as Unreal and Cry. He likes to play and develop games in his spare time.
Pooya Eimandar was born on 7th January 1986. He graduated in computer science and has a hardware engineering degree from Shomal University. He is also the author of DirectX 11.1 Game Programming, Packt Publishing.
He began his career working on various 3D simulation applications. In 2010, he founded BaziPardaz Game Studio, and since then, he has been leading an open source game engine (https://persianengine.codeplex.com/) at Bazipardaz.
He is currently working on a playout and CG editor tool for Alalam News Network. You can find more information about him at http://PooyaEimandar.com/.
Shaveen Kumar is a computer scientist and engineer. He graduated from Carnegie Mellon University in 2013 with a master's degree in entertainment technology and is working at Google. He works there as a graphics engineer and technical artist. His main interests are in GPU programming, parallel computing, game engine development, robotics, and computer vision.
More information about his work can be found at http://www.shaveenk.com.
M. Cihan Özer is a game developer and researcher in computer graphics. He started his career in game development and worked for several mobile and game companies.
He got his bachelor's degree from Ankara University, Turkey, and he is currently an MS student at Université de Montréal, Canada. Cihan's work focuses on realistic rendering and interactive techniques.
I would like to thank the authors of this book. It will help a lot of people who want to learn Qt and work with it. Also, I would like to thank the great people at Packt Publishing for giving me the opportunity to review this book.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.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
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.
Support files, eBooks, discount offers, and morehttps://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
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 that are new to Qt from the basics, such as objects, core classes, widgets, and so on, and new features in version 5.4, to a level where they can create a custom application with best practices when it comes to programming with Qt.
With a brief introduction on 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 before you try to create a game. 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, and build astonishing UIs for games. Toward the end of this book, you'll learn to exploit mobile device features, such as accelerators and sensors, to build engaging user experiences.
What this book covers
Chapter 1, Introduction to Qt, will familiarize you with the standard behavior that is required when creating cross-platform applications as well as show 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, will guide you through the process of installing a Qt binary release for desktop platforms, setting up the bundled IDE, and looking at various configuration options related to cross-platform programming.
Chapter 3, Qt GUI Programming, will show you how to create classic user interfaces with the Qt Widgets module. It will also familiarize you with the process of compiling applications using Qt.
Chapter 4, Qt Core Essentials, will familiarize you with 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 5, Graphics with Qt, describes the whole mechanism related to creating and using graphics in Qt in 2D and 3D. It also presents multimedia capabilities for audio and video (capturing, processing, and output)
Chapter 6, Graphics View, will familiarize 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 and possibly animate them.
Chapter 7, Networking, will demonstrate the IP networking technologies that are available in Qt. It will teach you how to connect to TCP servers, implement a reliable server using TCP, and implement an unreliable server using UDP.
Chapter 8, Scripting, shows you the benefits of scripting in applications. It will teach you how to employ a scripting engine for a game by using JavaScript. It will also suggest some alternatives to JavaScript for scripting that can be easily integrated with Qt.
Chapter 9, Qt Quick Basics, will teach you to program resolution-independent fluid user interfaces using a QML declarative engine and Qt Quick 2 scene graph environment. In addition, you will learn how to implement new graphical items in your scenes.
Chapter 10, Qt Quick, will show you how to bring dynamics to various aspects of a UI. You will see how to create fancy graphics and animations in Qt Quick by using the particle engine, GLSL shaders and built-in animation, and state machine capabilities, and you will learn how to use these techniques in games.
Chapter 11, Miscellaneous and Advanced Concepts, covers 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 the link https://www.packtpub.com/sites/default/files/downloads/Advanced_Concepts.pdf.
What you need for this book
All you need for this book is a Windows machine with the latest version of Qt installed. The examples presented in this book are based on Qt 5.4.
Qt can be downloaded from http://www.qt.io/download-open-source/.
Who this book is for
The expected readers of this book will be application and UI developers/programmers who have basic/intermediate functional knowledge of C++. The target audience also includes C++ programmers. No previous experience with Qt is required for you to read this book. Developers with up to a year of Qt experience will also benefit from the topics covered in this book.
Sections
In this book, you will find several headings that appear frequently (Time for action, What just happened?, Pop quiz, and Have a go hero).
To give clear instructions on how to complete a procedure or task, we use these sections as follows:
Time for action – heading
Action 1
Action 2
Action 3
Instructions often need some extra explanation to ensure they make sense, so they are followed with these sections:
What just happened?
This section explains the working of the tasks or instructions that you have just completed.
You will also find some other learning aids in the book, for example:
Pop quiz – heading
These are short multiple-choice questions intended to help you test your own understanding.
Have a go hero – heading
These are practical challenges that give you ideas to experiment with what you have learned.
Conventions
You will also find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: This API is centered on QNetworkAccessManager, which handles the complete communication between your game and the Internet.
A block of code is set as follows:
QNetworkRequest request;
request.setUrl(QUrl(http://localhost/version.txt
));
request.setHeader(QNetworkRequest::UserAgentHeader, MyGame
);
m_nam->get(request);
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
void FileDownload::downloadFinished(QNetworkReply *reply) { const QByteArray content = reply->readAll();
m_edit->setPlainText(content);
reply->deleteLater();
}
Any command-line input or output is written as follows:
git clone git://code.qt.io/qt/qt5.git cd qt5 perl init-repository
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: On the Select Destination Location screen, click on Next to accept the default destination.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/GameProgrammingUsingQt_ColoredImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Chapter 1. Introduction to Qt
In this chapter, you will learn what Qt is and how it evolved. We will pay special attention to the differences between Qt's major versions 4 and 5. Finally, you will learn to decide on which of the available Qt licensing schemes to choose for our projects.
The cross-platform programming
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 figure), where Qt hides all platform-dependent aspects from the application code:
The cross-platform programmingOf course, at times we need to use some functionality that Qt doesn't provide. In such situations, it is important to use conditional compilation like the one used in the following code:
#ifdef Q_OS_WIN32
// Windows specific code
#elif defined(Q_OS_LINUX) || defined(Q_OS_MAC)
// Mac and Linux specific code
#endif
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register there to have the files e-mailed directly to you.
What just happened?
Before the code is compiled, it is first fed to a preprocessor that may change the final text that is going to be sent to a compiler. When it encounters a #ifdef directive, it checks for the existence of a label that will follow (such as Q_OS_WIN32), and only includes a block of code in compilation if the label is defined. Qt makes sure to provide proper definitions for each system and compiler so that we can use them in such situations.
Tip
You can find a list of all such macros in the Qt reference manual under the term QtGlobal
.
Qt Platform Abstraction
Qt itself is separated into two layers. One is the core Qt functionality that is implemented in a standard C++ language, which is essentially platform-independent. The other is a set of small plugins that implement a so-called Qt Platform Abstraction (QPA) that contains all the platform-specific code related to creating windows, drawing on surfaces, using fonts, and so on. Therefore, porting Qt to a new platform in practice boils down to implementing the QPA plugin for it, provided the platform uses one of the supported standard C++ compilers. Because of this, providing basic support for a new platform is work that can possibly be done in a matter of hours.
Supported platforms
The framework is available for a number of platforms, ranging from classical desktop environments through embedded systems to mobile phones. The following table lists down all the platforms and compiler families that Qt supports at the time of writing. It is possible that when you are reading this, a couple more rows could have been added to this table:
A journey through time
The development of Qt was 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:
A journey through timeThis allowed programmers to only link to the functionality that they used in their applications, reducing the memory footprint and 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 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, they decided to introduce Qt to more developers by adding a very liberal LGPL license 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 eye candy. 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 nonmobile-related work, channeling all efforts to make Qt Quick faster, easier, and more widespread. Qt 4 was already in the market for 7 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.
Nokia did not manage to finish working on Qt 5.0. As a result of an unexpected turn over 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 in December of the same year.
New in Qt 5
The API of Qt 5 does not differ much from that of Qt 4. Therefore, Qt 5 is almost completely source compatible with its predecessor, which means that we only need a minimal effort to port the existing applications to Qt 5. This section gives a brief introduction to the major changes between versions 4 and 5 of Qt. If you are already familiar with Qt 4, this can serve as a small compendium of what you need to pay attention to if you want to use the features of Qt 5 to their fullest extent.
Restructured codebase
The biggest change compared to the previous major release of Qt and the one that is immediately visible when we try to build an older application against Qt 5 is that the whole framework was refactored into a different set of modules. Because it expanded over time and 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.
Qt Essentials
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. Some of the modules are explained as follows:
The QtCore 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 is much smaller compared with the same module from Qt 4, as the support for widgets and printing has been moved to separate modules. Qt GUI contains classes that are used to manipulate windows that can be rendered using either the raster engine (by specifying QSurface::RasterSurface as the surface type) or OpenGL (QSurface::OpenGLSurface). Qt supports desktop OpenGL as well as OpenGL ES 1.1 and 2.0.
The Qt Network module brings support for IPv4 and IPv6 networking using TCP and UDP as well as by controlling the device connectivity state. Compared to Qt 4, this module improves IPv6 support, adds support for opaque SSL keys (such as hardware key devices) and UDP multicast, and assembles MIME multipart messages to be sent over HTTP. It also 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.
Qt SQL brings a framework that is used to manipulate SQL databases in an abstract way.
Qt WebKit is a port of the WebKit 2 web browser engine to Qt. It provides classes to display and manipulate web content and integrates with your desktop application.
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 that are arranged using a special layout engine. It also contains the implementation of