Game Programming Using Qt: Beginner's Guide - Witold Wysota - E-Book

Game Programming Using Qt: Beginner's Guide E-Book

Witold Wysota

0,0
47,99 €

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

Mehr erfahren.
Beschreibung

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

Who This Book Is For

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

In Detail

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 approach

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

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 697

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



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

https://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 PacktCopy and paste, print, and bookmark contentOn 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 1Action 2Action 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.

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:

Of 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:

Platform

QPA plugins

Supported compilers

Linux

XCB (X11) and Wayland

GCC, LLVM (clang), and ICC

Windows XP, Vista, 7, 8, and 10

Windows

MinGW, MSVC, and ICC

Mac OS X

Cocoa

LLVM (clang) and GCC

Linux Embedded

DirectFB, EGLFS, KMS, and Wayland

GCC

Windows Embedded

Windows

MSVC

Android

Android

GCC

iOS

iOS

LLVM (clang) and GCC

Unix

XCB (X11)

GCC

RTOS (QNX, VxWorks, and INTEGRITY)

qnx

qcc, dcc, and GCC

BlackBerry 10

qnx

qcc

Windows 8 (WinRT)

winrt

MSVC

Maemo, MeeGo, and Sailfish OS

XCB (X11)

GCC

Google Native Client (unsupported)

pepper

GCC

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:

This 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 an object-oriented 2D graphics canvas called Graphics View. When porting Qt 4 applications to Qt 5, it is a good idea to start by enabling support of the widgets module (by adding QT += widgets to the project file) and then work your way down from here.Qt Quick is an extension of Qt GUI, which provides means to create lightweight fluid user interfaces using QML. It is described in more detail later in this chapter as well as in Chapter 9, Qt Quick Basics.

Tip

There are also other modules in this group, but we will not focus on them in this book. If you want to learn more about them, you can look them up in the Qt reference manual.

Qt Add-ons

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.

Some of the most important modules are QtConcurrent for parallel processing, Qt Script that allows us to use JavaScript in C++ applications, Qt3D that provides high-level OpenGL building blocks, and Qt XML Patterns that helps us to access XML data. Many others are also available, but we will not cover them here.

Qt Quick 2.0

The largest upgrade to Qt functionality-wise is Qt Quick 2.0. In Qt 4, the framework was implemented on top of Graphics View. This proved to be too slow when used with low-end hardware even with OpenGL ES acceleration enabled. This is because of the way Graphics View renders its content—it iterates all the items in sequence, calculates and sets its transformation matrix, paints the item, recalculates and resets the matrix for the next item, paints it, and so on. Since an item can contain any generic content drawn in an arbitrary order, it requires frequent changes to the GL pipeline, causing major slowdowns.

The new version of Qt Quick instead uses a scene-graph approach. It describes the whole scene as a graph of attributes and well-known operations. To paint the scene, information about the current state of the graph is gathered and the scene is rendered in a more optimal way. For example, it can first draw triangle strips from all items, then render fonts from all items, and so on. Furthermore, since the state of each item is represented by a subgraph, changes to each item can be tracked and it can be decided whether the visual representation of a particular item needs to be updated or not.

The old QDeclarativeItem class was replaced by QQuickItem, which has no ties to the Graphics View architecture. There is no routine available where you can directly paint the item, but there is a QQuickPaintedItem class available that aids in porting old code by rendering content based on QPainter to a texture and then rendering that texture using a scene-graph. Such items are, however, significantly slower than those directly using the graph approach, so if performance is important, they should be avoided.

Qt Quick plays an important role in Qt 5 and it is very useful to create games. We will cover this technology in detail in Chapters 9, Qt Quick Basics and Chapter 10, Qt Quick.

Meta-objects

In Qt 4, adding signals and slots to a class required the presence of a meta-object (that is, an instance of a class that describes another class) for that class. This was done by subclassing QObject, adding the Q_OBJECT macro to it, and declaring signals and slots in special scopes of the class. In Qt 5, this is still possible and advised in many situations, but we now have new interesting possibilities.

It is now acceptable to connect a signal to any compatible member function of a class or any callable entity, such as a standalone function or function object (functor). A side-effect is a compile-time compatibility check of the signal and the slot (as opposed to the runtime check of the "old" syntax).

C++11 support

In August 2011, ISO approved a new standard for C++, commonly referred to as C++11. It provides a number of optimizations and makes it easier for programmers to create effective code. While you could use C++11 together with Qt 4, it didn't provide any dedicated support for it. This has changed with Qt 5, which is now aware of C++11 and supports many of the constructs introduced by the new version of the language. In this book, we will sometimes use C++11 features in our code. Some compilers have C++11 support enabled by default, in others, you need to enable it. Don't worry if your compiler doesn't support C++11. Each time we use such features, I will make you aware of it.

Choosing the right license

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, better consult a professional lawyer.

An open source license

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 decide between GPL 3.0 and LGPL 2.1 or 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 might 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.

The open source edition of Qt can be downloaded directly from http://www.qt.io.

A commercial license

All these 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 in 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.

Note

To buy a commercial license, go to http://qt.io/buy.

Summary

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 your development machine.

Chapter 2. Installation

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. In addition to this, the chapter will describe the process of building Qt from the source code, which can be useful for customizing your Qt installation as well as getting a working Qt installation for embedded platforms. By the end of this chapter, you will be able to prepare your working environment for both desktop and embedded platforms using tools included in the Qt release.

Installing the Qt SDK

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 will prefer this approach.

Time for action – installing Qt using an online installer

First, go to http://qt.io and click on Download. This should bring you to a page containing a list of options for different licensing schemes. To use the open source version, choose the Open Source edition licensed under GPL and LGPL. Then, you can click on the Download Now button to retrieve the online installer for the platform that you are currently running on or you can click on any of the header sections to reach a more comprehensive list of options. The links to online installers are at the beginning of the list, as shown in the following screenshot. Click and download the one suited to your host machine:

When the download completes, run the installer, as shown:

Click on Next and after a while of waiting as the downloader checks remote repositories, you'll be asked for the installation path. Be sure to choose a path where you have write access (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 choices of components that you wish to install, as shown in the following screenshot. You will be given different choices depending on your platform.

Choose whichever platforms you need, for example, to build native and Android applications on Linux, choose both gcc-based installation and one for the desired Android platform. When on Windows, you have to make additional choices. When using Microsoft compilers, you can choose whether to use native OpenGL drivers (the versions with the OpenGL suffix) or to emulate OpenGL ES using DirectX calls. If you don't have a Microsoft compiler or you simply don't want to use it, choose the version of Qt for the MinGW compiler. If you don't have a MinGW installation, don't worry—the installer will also install it for you.

After choosing the needed components and clicking on Nextagain, you will have to accept the licensing terms for Qt by marking an appropriate choice, as shown in the following screenshot. After clicking 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.

What just happened?

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. You can see that if you ever decide to install another version of Qt, it will not conflict with your existing installation. Furthermore, for each version, you can have a number of platform subdirectories that contain the actual Qt installations for particular platforms.

Setting up Qt Creator

After Qt Creator starts, you should be presented with the following screen:

The program should already be configured properly for you to use the version of Qt and compiler that were just installed, but let's verify that anyway. From the Tools menu, choose Options. Once a dialog box pops up, choose Build & Run from the side list. This is the place where we can configure the way Qt Creator builds our project. A complete build configuration is called a kit. It consists of a Qt installation and a compiler that will be executed to perform the build. You can see tabs for all the three entities in the Build & Run section of the Options dialog box.

Let's start with the Compilers tab. If your compiler was not autodetected properly and is not in the list, click on the Add button, choose your compiler type from the list, and fill the name and path to the compiler. If the settings were entered correctly, Creator will autofill all the other details. Then, you can click on Apply to save the changes.

Next, you can switch to the Qt Versions tab. Again, if your Qt installation was not detected automatically, you can click on Add. This will open a file dialog box where you will need to find your Qt installation's directory wherein all the binary executables are stored (usually in the bin directory) and select a binary called qmake. Qt Creator will warn you if you choose a wrong file. Otherwise, your Qt installation and version should be detected properly. If you want, you can adjust the version name in the appropriate box.

The last tab to look at is the Kits tab. It allows you to pair a compiler with the Qt version to be used for compilation. In addition to this, for embedded and mobile platforms, you can specify a device to deploy to and a sysroot directory containing all the files needed to build the software for the specified embedded platform.

Time for action – loading an example project

Qt comes with a lot of examples. Let's try building one to check whether the installation and configuration were done correctly. In Qt Creator, click on the Welcome button on the top-left corner of the window to go the initial screen of the IDE. On the right-hand side of the page that appears (refer to the previous screenshot) there are a couple of tabs among which one of them happens to be called Examples. Clicking on that tab will open a list of examples with a search box. Make sure that the version of Qt you just installed is chosen in the list next to the search box. In the box, enter aff to filter the list of examples and click on Affine Transformations to open the project. If you are asked whether you want to copy the project to a new folder, agree. Qt Creator will then present you with the following window:

What just happened?

Qt Creator loaded the project and set a view that will help us to learn from example projects. The view is divided into four parts. Let's enumerate them starting from the left side. First there is Qt Creator's working mode selector that contains an action bar, which allows us to toggle between different modes of the IDE. Then, there is the project view that contains a list of files for the project. Next comes the source code editor, displaying the main part of the project's source code. Finally, far to the right, you can see the online help window displaying the documentation for the opened example.

Time for action – running the Affine Transformations project

Let's try building and running the project to check whether the building environment is configured properly. First, click on the icon in the action bar directly over the green triangle icon to open the build configuration popup, as shown in the following screenshot: