47,99 €
A complete guide to designing and building fun games with Qt and Qt Quick 2 using associated toolsets
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.
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.
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:
Seitenzahl: 697
Veröffentlichungsjahr: 2016
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
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
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.
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.
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.
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.
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.
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.
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/.
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.
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:
Instructions often need some extra explanation to ensure they make sense, so they are followed with these sections:
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:
These are short multiple-choice questions intended to help you test your own understanding.
These are practical challenges that give you ideas to experiment with what you have learned.
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.
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.
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.
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.
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 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.
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.
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.
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:
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.
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.
You can find a list of all such macros in the Qt reference manual under the term "QtGlobal".
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.
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
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.
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.
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.
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:
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.
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.
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.
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).
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.
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.
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:
The open source edition of Qt can be downloaded directly from http://www.qt.io.
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.
To buy a commercial license, go to http://qt.io/buy.
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.
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.
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.
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.
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.
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.
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:
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.
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:
