Home Programming Application Development with Qt Creator - Second Edition

Application Development with Qt Creator - Second Edition

books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with Qt Creator
About this book
Publication date:
November 2014
Publisher
Packt
Pages
264
ISBN
9781784398675

 

Chapter 1. Getting Started with Qt Creator

Qt Creator is an integrated software development environment that supports both traditional C++ application development as well as development using the Qt project's libraries (collectively called Qt and pronounced as cute).

Qt is available under a commercial license as well as under GPL v3 and LGPL v2. Its development dates all the way back to 1991. For the first ten years of its life, it was a cross-platform toolkit for Windows and X11; by 2001, support for Mac OS X was added.

In this chapter, we will take a look at everything you need to get started:

  • Where to download Qt Creator for Linux, Mac OS X, and Windows

  • How to ensure that your basic configuration is running

  • A quick look at a simple QtGui application as well as a Qt Quick application

 

Downloading Qt and Qt Creator


Qt, the cross-platform toolkit behind Qt Creator, has had a long and illustrious history. Presently a project of Digia, it has its own URL at http://qt-project.org/ and has both commercial and non-commercial licenses. To get started with the non-commercial version for free, go to http://qt-project.org/downloads to see something similar to what the following screenshot shows:

Downloading Qt Creator

Tip

One of the most popular platforms for application development with Qt is Linux. On many Linux variants—notably Ubuntu, my personal favorite—you can get Qt Creator using the package manager. On my Ubuntu box, Qt Creator is just a sudo apt-get install qtcreator command away. You'll get a version of Qt that matches your flavor of Linux, although it might not be the latest and greatest build from Digia.

By following the link and downloading Qt, you should now have Qt, Qt Creator, and the MinGW toolkit for developing software on Windows. If you're developing on Linux or Mac, the process will be similar, although it won't include MinGW.

Some downloads include the C++ compiler and the linker that you need for your development, while others don't. For example, on Windows, there's a variant that includes the MinGW tool chain, so you have everything you need to build applications. However, you can also download Qt Creator for Windows that uses the Microsoft Visual Studio compilers. So, if you prefer using Visual Studio for your compilation and Qt Creator as your IDE, this is also an option. On Mac OS X, you'll need to have Xcode and the command-line development tools installed first; you can download Xcode from the Mac OS X App Store and then use Xcode to download the command-line development tools.

Once the installer downloads, run it in the usual way. It'll launch an installation wizard for your platform, and installation should typically take about 3 to 4 minutes. You'll want to have plenty of disk space. Qt Creator doesn't consume that much disk space, but software development does; figure at least 500 MB for the tools and libraries, and budget a few gigabytes free on your main drive for your source code, intermediate object files, debugging symbols, and of course, your compiled application. (It is especially important to plan for this if you're running Qt Creator on a virtual machine; make sure that the virtual hard drive for your virtual machine image has plenty of disk space.)

You should also ensure that your development box has plenty of RAM; the more the better. Qt Creator runs happily on 2 GB of RAM, but the compiler and linker used by Qt Creator can run a lot faster if they have more RAM available.

 

Finding your way around Qt Creator


The following screenshot shows what you will see when you launch Qt Creator for the first time. Let's take a closer look at each portion of the screen, shown as follows:

The main window, which currently shows the buttons for New Project and Open Project, is your workspace. The workspace also includes links to the Qt projects, examples, and tutorials as well as Qt's developer documentation, such as its online community and blogs. Under normal conditions, this will be located where you'll see the source code for your application. Along the left-hand side of the screen are a series of icons that let you select various views in your application. They are as follows:

  • The Welcome mode, which shows basic information about Qt Creator

  • The Edit mode, which lets you edit the files that make up your application

  • The Design mode, which lets you use Qt Designer to design the user interface for your application

  • The Debug mode, which lets you debug your application while it's running, including doing things such as viewing the memory and variables, setting breakpoints, and stepping through the application

  • The Projects mode, which lets you adjust the build and link settings for your project

  • The Analyze mode, which lets you profile your application's runtime performance

  • The Help mode, which provides documentation on Qt Creator and the Qt framework

Let's create a new project using C++.

 

Your first application – Hello World


In Qt Creator, select New File or Project… from the File menu. Qt Creator will present you with the New Project wizard, which lets you choose the kind of project you want to create, give it a name, and so forth. To create your first application, perform the following steps:

  1. Select New File or Project… if you haven't done so already.

  2. Qt Creator presents you with a dialog that has a dizzying array of project choices. Choose Application, then Qt Console Application, and then click on Choose….

  3. Qt Creator asks you for a name and a path to the directory where you want to store the files for the project. For the name, enter HelloWorldConsole and choose a path that makes sense to you (or accept the default). Then, click on Next.

  4. Qt Creator can support various kits and libraries against which you can build an application. Select the Desktop Qt Kit, which should have been installed by default, leaving both the Release and Debug choices checked. Then, click on Next.

  5. In the next step, Qt Creator prompts you about the version control for your project. Qt Creator can use your installed version control clients to perform change tracking for your project. For now, skip this and leave Add to version control set to None. Then, click on Finish.

Qt Creator creates your project and switches to the Edit view. In the source code editor for the main.cpp file, enter the following code:

#include <QCoreApplication>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
    
    cout << "Hello world!";

  return a.exec();
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. 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.

The QCoreApplication task handles the entire system startup for an application, and every Qt Console app needs to create one and call its exec method as part of your main method. It sets up Qt's event handler and provides a bunch of porting helpers to determine things such as your application directory, library paths, and other details.

For a console application, that's all you need; you can freely mix and match Qt classes with the C++ standard library and Standard Template Library (although once you master Qt's foundation classes, many STL constructs might feel somewhat limiting).

Next, let's compile and run the application. There are several ways to do this. You can:

  • Click on the green Run arrow below the Help view button on the left to run the application

  • Hit F5 to build and run your application in the debugger

  • Click on Start Debugging… from the Debug menu

  • Click on the green Run arrow with the bug over the arrow in order to debug the application on the left

  • Choose Run from the Build menu (or hit Ctrl + R)

    Tip

    If you only want to build the application, you can click on the hammer icon below the Run and Debug icons.

When you choose one of these options, Qt Creator invokes the compiler and the linker to build your application. If you choose the Debug option, Qt Creator switches to the Debug view (which we will discuss in detail in the next chapter) as it starts your application.

Once the application starts, you'll see the Hello world! message in a console view.

 

Hello World using the QtGui library


One of Qt's strengths is its rich collection of GUI elements that you can use to create windowed applications. Making a GUI application is similar in principle to making a console application; instead of choosing Qt Console Application, select Qt Widgets Application from the New dialog presented when you choose New File or Project. Try it now:

  1. First, close the current file and project by clicking on Close All Projects and Editors from the File menu.

  2. Next, click on New File or Project… again and click on Qt Widgets Application from the first step of the wizard.

  3. Walk through the wizard again, naming your project HelloWorldGui.

  4. Then, select the default kit. The New project wizard will prompt you for the name of the class implementing your main window. Leave the subclass as QMainWindow and the name as MainWindow. Skip the version control dialog portion of the wizard.

Qt Creator creates a default subclass of the class that provides the platform's basic window in the mainform.h and mainform.cpp files, and creates a form that will contain the widgets for your application's window.

The following screenshot shows a default form as you're editing it in Qt Designer. If you run the application at this point, you'll see an empty window. Instead, double-click on the Forms folder in the project tree (the second pane) of Qt Creator and then double-click on the mainwindow.ui file. Qt Creator switches to the Design view, and you'll see something similar to the next screenshot:

On the left-hand side is a list of the layouts that you can choose to organize widgets, such as spacers, views, containers, buttons, and other widgets; on top of this, there are various edit and layout options. In the middle is a view of the layout of your application's main window, and to the right are panes with a hierarchy of objects in your main window and the properties of any item that you click on in the main window.

While we will explore Qt Designer more in Chapter 3, Designing Your Application with Qt Designer, you can get a feel of using it to build a simple UI. Begin by ensuring that you're in the Designer mode:

  1. Where it says Type Here, right-click and choose Remove menu bar.

  2. Drag a label (under Display Widgets in the left-hand side pane) and drop it in the window preview in the center pane.

  3. Double-click on the label that appears and type Hello world!.

  4. Grab a corner of the label and resize it so that the entire text is shown. You can also move it around in the window.

  5. Note that when you click on the label, the Property field in the lower-right pane is updated to show the properties of your new label.

  6. Drag a button (under Buttons in the left-hand side pane) and drop it in the window preview in the center pane.

  7. Double-click on the button and change its text to Exit.

  8. With the new button selected, change the objectName field in the Property browser to exitButton.

  9. Right-click on the button and select Go to slot…. A window appears with a list of slots (for now, you can think of a slot as something that is triggered on an action; we will discuss them more in Chapter 2, Building Applications with Qt Creator).

  10. Choose clicked() from the list that appears.

  11. Qt Creator returns to the Edit view for your mainwindow.cpp file. Change it to read as follows:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QApplication>
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    voidMainWindow::on_exitButton_clicked()
    {
        QApplication::exit();
    }

Before running your application, let's be sure that you understand the implementation of the MainWindow class. The constructor of the MainWindow class loads the description of the user interface for the main window and sets it up using the Qt Creator-generated class Ui::MainWindow. The destructor deletes the implementation of the code layout, and the on_exitButton_clicked method simply terminates the application by calling the exit static method implemented by the QApplication class.

Finally, we have to add the on_exitButton_clicked method declaration to mainwindow.h if it's not already added. Double-click on this file in the browser on the left and make sure that it reads as follows:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespaceUi {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    
private slots:
    void on_exitButton_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

The key lines you need to add are highlighted in the previous listing.

We'll learn more about signals and slots in the next chapter; for now, it's enough for you to know that you're declaring a private function to be triggered when you click on the button.

Run the application. It should open a single window with the text Hello World!; clicking on the Exit button in the window (or on the close box in the upper-right corner) should close the application. At this point, if you think you want to learn more about Qt Widget applications, go ahead and try dragging other GUI items to the window, or explore the help documentation for Qt Widget applications by switching to the Help view and clicking on Qt GUI from the list of help items.

 

Hello World using Qt Quick


Qt Quick is Qt's newer declarative framework for the user interface, and with this, it's incredibly easy to create fluid applications with animated transitions and flowing user interfaces. Using Qt Quick, you can describe your user interface using QML, a JavaScript-like language that lets you declare user interface elements and how they relate; the Qt Quick runtime does most of the heavy lifting in the implementation of your application.

By now, you can guess how to create a Qt Quick project. Choose New File or Project from the File menu, click on Qt Quick Application, and then follow the wizard.

The wizard will ask you one additional question: the Qt Quick version to use. You should simply choose the latest version. Once you walk through the wizard, you end up with a simple application that actually displays Hello World in its own window. Here's the code that it supplies:

import QtQuick 2.3

Rectangle {
    visible: true
    width: 360
    height: 360

    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }

    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }
}

If you know JavaScript, the syntax of this might look a little familiar, but it's still different. The first two lines are the import statements; they indicate which classes should be available to the QML runtime. At a minimum, all of your Qt Quick applications must import QtQuick, as this one does.

The QML follows. It declares a parent rectangle of 360 × 360 pixels that determines the size of the application window. Inside the rectangle are two objects: a Text object and MouseArea. The Text object is just that: a label with the text Hello World placed in the center of the rectangle. Note that the value of the text property is actually the result of a function call to the qsTr function, which is Qt's built-in localization function. This looks at application resources to return the localized version of Hello World if it has been provided.

MouseArea is an object that takes user input and can execute functions based on this input; it's sized to fit the parent (anchors.fill is set to parent) and responds when clicked by executing the function assigned to the onClicked property. This onClicked function just exits the application by calling the Qt class's quit function.

At this point, you can run the application in the usual way, and you'll see a window with the text Hello World in the center of the window.

While the principles are similar, the Qt Quick designer is very different from the Qt Widgets designer. Take a look at the next screenshot:

There are some obvious similarities: both designers show a list of things that you can add to a view, along with a hierarchy of the objects in the view and the properties of individual objects.

However, there are far fewer Qt Quick widgets than there are Qt widgets, and the widgets in Qt Quick don't match the look and feel of the native platform to nearly the same extent. That's by design; Qt Widgets is for building conventional applications that match the native platform by using native controls and a native look and feel, while Qt Quick is used for creating device-independent applications with their own look and feel. For example, you'd probably write an enterprise data collection application using Qt Widgets, while you'd create a media center application using Qt Quick.

However, the manner of using the designer is the same in both cases. Let's add another MouseArea to the main view and give it something to do:

  1. Select main.qml from the list of files in Qt Creator and click on Design to see the Design view.

  2. In the Library pane, select QML Types and scroll down until you see Rectangle. Drag the rectangle to the center pane and drop it somewhere above the Hello World label. You might need to resize the rectangle so that the label is still visible.

  3. With the rectangle selected in the window pane, enter a color for your rectangle under Colors.

  4. Now, drag a MouseArea object out of the Library pane and drop it on your new rectangle.

  5. With the MouseArea object selected, click on Layout in the Properties tab and mouse over the layouts until you see Fill to Parent. (This is the fifth icon below Anchors and looks like a box with a border.) Click on it.

  6. Go back to the Edit view and modify main.qml to look similar to the following code snippet:

    Import QtQuick 2.3
    import QtQuick.Window 2.2
    
    Window {
        visible: true
        width: 360
        height: 360
    
        MouseArea {
            anchors.fill: parent
            onClicked: {
                Qt.quit();
            }
        }
    
        Text {
            id: text
            text: qsTr("Hello World")
            anchors.centerIn: parent
        }
    
        Rectangle {
            id: rectangle1
            x: 135
            y: 50
            width: 100
            height: 100
            color: "#708fff"
    
            MouseArea {
                id: mouseArea1
                anchors.fill: parent
                onClicked: text.text = qsTr("Hi there!")
            }
        }
    }

You can see that most of the changes were made by the Design view; it added a rectangle inside the original MouseArea object and another MouseArea object inside it. You will need to add a line giving the text element an ID of the text and the onClicked handler to the new MouseArea object that you dragged out in the Design view. The id property lets other QML access the text field by name (in this case, its name is simply text), and the onClicked handler changes the contents of the text item's text property to the text Hi there!.

It's worth making a note of qsTr here; you don't have to add any text to the application resources to get basic localization working. This is unlike most other platforms where localization occurs by providing keys to values in local files for strings with a default value for the unlocalized strings.

Run the application. You'll see your rectangle above the text Hello World, and clicking on the rectangle changes the text to read Hi there!.

 

Summary


Getting Qt Creator is easy; it's just a web download away, or on most Linux platforms, it's an optional installation through the native package manager (although the versions delivered by a package manager might be slightly older than those you get from the Qt Project's website).

Qt Creator organizes its source code for you in projects; when you first launch it, you can either create a default project or create a new project to contain the source code and resources for your application. Inside Qt Creator are all the options you need to compile and debug your application. In addition, it supports designer tools for developing both Qt Widgets and Qt Quick applications.

In the next chapter, we'll dig into the details of how to configure Qt Creator for compiling and editing your code, including how to add source files to your project, configure compiler and linker options, add dependencies to third-party libraries, and so on.

Latest Reviews (7 reviews total)
Ich habe eigentlich nach einem Buch zu QML gesucht und fand gleich 10 Bücher zu Themen die in anderen Verlagen zu kurz kommen, und das zum genialen Sonderpreis
fast and easy to do purchasing ...
ebook is good enough, goodbye
Application Development with Qt Creator - Second Edition
Unlock this book and the full library FREE for 7 days
Start now