Installing and configuring Qt Creator. Why I love Qt and you all should love it too Qt programming for beginners

A simple example for manual assembly

For a better understanding of Qt, it would be correct to manually build at least a simple example in the console. The assembly technique is the same for projects of any size and it is important to understand how it is done.

Let's look at a simple example of a GUI application that opens an empty window on the screen. Select a directory on the disk where we will create the file main.cpp with the following content. Line numbering has been added to the example to simplify further comments on the example. It should be understood that line numbering should not be included in the working file, since it is not part of the valid C++ expression syntax.

01. #include 02. #include 03. 04. int main(int argc, char *argv) 05. ( 06. QApplication app(argc, argv); 07. QWidget wgt; 08. wgt.setWindowTitle(tr("Hello world")); 09. 10 . wgt.show(); 11. return app.exec();

Lines 01 and 02 include header files QApplication And QWidget, which, among other things, contains class declarations QApplication And QWidget. In our example, we create instances of these classes.

It is worth noting the convenient tradition of naming header files used in Qt. Since version 4 of Qt, if you needed a class named Qxxx, then most likely its definition is in the header file Qxxx.

In this example, the class QApplication We are interested in as the organizer of the cycle of collecting messages that will arrive in the window of our GUI application. See line 11 (starting the window message loop). Class QApplication implemented in the likeness of a Singleton. For those who are not familiar with this term from the theory of design patterns (or, patterns, from the English. patterns) let's give a little explanation. The essence of a singleton is that the implementation of a class prevents the possibility of creating more than one instance of a given class. This feature is important to us because it implies the possibility of defining a global variable inside the Qt library with a pointer to a single instance of a given class. See description for symbol qApp in the Qt help.

The Qt library uses widget terminology. widget- contraption, device) as an element of the GUI interface. The minimum common set of properties of such elements is represented by the class QWidget.

Lines 06 and 07 create the application and widget class objects. In both cases, objects are created statically. The lifetime of such objects is limited by the statement block (...) in which they were created. As soon as the execution of the program code reaches the closing bracket, both of these objects are automatically destroyed. Thus, in this example we will not think about how to destroy Qt objects and will look at this issue later.

When creating an object QApplication a parameterized constructor is used to which the application launch arguments are passed (copied from the main() function arguments). Inside the class object, these arguments are parsed. The application class supports a number of launch parameters, which can be found in the help for the corresponding constructor QApplication. Launch parameters not included in this list should be analyzed independently. At the end of this lesson, having placed several controls in the main application window, we will suggest experimenting with the -style launch parameter, for which, in any Qt build, the following values ​​are possible: motif, windows, platinum.

Line 08 changes one of the widget object's attributes. Using the setWindowTitle() method, we set our own text for the title of our future window. Note that the string image is wrapped in a call to the translate function tr(). This is a requirement to internationalize the application. For all such wrappers, special Qt tools can be used to create special files with translations into different languages, which can be used in the application to perform automatic replacements. Typically, such files are included in the application build as resources.

Line 10 opens the application window. Before Qt4, before opening a window, the widget was explicitly declared as the main widget of the application. This was done using the following code.

App.setMainWidget(&wgt);

Starting from Qt4, such communication is performed automatically by accessing the global pointer qApp to an instance of the application class.

Line 11 starts the operating system message processing loop directed to the application window. The loop ends when any of the application closing commands are executed. The application exit code is returned by exec() when the method exits. It is this code that becomes the return code of the main() function by passing it through the operator return.

Now let's try to build the application. The easiest way to do this is on Linux. To do this, you just need to open the console and run some commands, which we will now describe. For Windows, such work may require setting paths to the directory where the qmake utility from the Qt SDK is located. This utility implements the rules of the QMake project build system.

First we need to find out what is available to us from the console. If we are in the bash (*nix) console, then this is quite simple. Type the command qmake and press tab twice. We should see a list of all commands that begin with the combination qmake. For example, in my case I see two commands: qmake And qmake-qt4. This means that I have two versions of the library installed from the repository. Team qmake corresponds to the Qt5 version (the default is for the latest version), and the command qmake-qt4 corresponds accordingly to Qt4. Now, depending on which command I use, I will either build using the Qt5 version or using the Qt4 version.

If everything in our system is configured normally and the Qt SDK versions are successful, then the project should be built using the following three commands.

$ qmake -project $ qmake $ make

The first command will create a project file. The project file has the suffix .pro. In the context of Windows, it would be correct to say "extension pro". Concepts file name suffix And file extension mean completely different things, although they seem similar. Make sure to use it correctly.

The second command should create a compilation script file - Makefile. The third command should run a compilation script that should produce an executable application file.

If this does not happen, then we will try to find the problem.

Open the project file. Try to find the following line there.

QT += gui

If such a line is not there, then you should add it, otherwise, depending on the SDK version, the project may be perceived as a console project and the paths to the GUI class header files will not be included in it. This will result in compilation errors stating that included header files were not found.

Keep in mind that if you are dealing with Qt SDK version 5, then this definition must also include the group widgets as shown below.

QT += gui widgets

An example of creating a GUI application template from QtCreator

Open QtCreator. To create a new project, launch the project creation wizard from the "File->New File or Project..." menu. In the window that opens on the first page of the wizard, you are prompted to select a template for the future project. For the "Application" project group, select the "Qt GUI Application" option and click on the "Choose" button to go to the next page of the wizard.

On the second page of the project creation wizard, you are asked to select a project name and its location directory. Using the specified project name, a subdirectory will be created in which the project files will be located. The subdirectory will be created in the specified placement directory. Thus, the project name must be determined by the rules that the directory name must obey. However, to avoid problems, do not use Russian letters and spaces. Use English letters, numbers and underscores and dashes (minus sign). Let our project be called app1. Let's write it in the line name, and in the line for selecting the project directory we will indicate the directory where we will continue to create projects on Qt. Paths with Russian letters and spaces should be avoided. Sooner or later, they can cause problems. If you need to remember this path for next time, check the "Use as default project location" checkbox. Click on the "Next" button to go to the next page of the wizard.

On the third page of the project creation wizard, you are asked to select a Qt SDK from the list of those found and registered in QtCreator. Select the Qt4 option. For the selected SDK version, you must define project build profiles. The "Release" and "Debug" options are offered. The "Release" build does not contain debugging symbols in the executable file and is recommended for transfer to real use. In all other cases, it is more convenient to use the "Debug" build. In the current example, the choice of assembly does not matter. You can leave both profiles enabled. To the right of the profile name there is an input field in which the path along which the corresponding assembly will be performed is written. Often these paths are edited based on different traditions. In our example, we can leave these paths unchanged. Click on the "Next" button to go to the next page of the wizard.

On the fourth page of the project creation wizard, you are asked to select the class name for the main form of the project, the base class from which the main form of the project should be inherited, and the names of the files where the interface and implementation of the created class of the main form will be located. In addition, the page should indicate whether visual form design will be used. Since we will not be using visual design, we should make sure that the "Generate form" checkbox is unchecked.

The most interesting thing on the fourth page of the New Project Wizard is choosing a base class to create a form class. Three options are offered.

  1. QMainWindow- in most cases, the most suitable choice. By inheriting from this class, we get ready-made tools for placing a menu, status bar and central field, which can be implemented both in the SDI (Single Document Interface) style and in the MDI (Multi Document Interface) style.
  2. QWidget— this class is the simplest widget. In Qt terminology, this is the simplest element with which some kind of graphical area on the screen is associated. As a base class for the main window, it is used, as a rule, when creating simple single-form applications and is excellent for initial “student” purposes due to the fact that it does not contain anything “superfluous”.
  3. QDialog— base class for creating modal dialog boxes.

For our example, we will choose as the base class, the simplest option is QWidget. The names for the main class of the form and for the files where its interface and implementation will be located can be left as default values. Click on the "Next" button to go to the next page of the wizard.

The fifth page of the project creation wizard allows you to determine the relationship of the project being created with already open projects and specify the choice of any available project version control system. In the current example, we are not interested in these features, so we should complete the wizard by clicking the "Finish" button.

The steps to create a project may differ slightly in different versions of QtCreator, but essentially, here are the main points that you should understand when creating a GUI project. The current description was made based on QtCreator version 2.7.0.

After completing the New Project Wizard in QtCreator, a view with the created project will open. Run the project to check your development environment settings. If everything is in order, then the created project template should compile and run. To launch a project normally, you can click on the button with a green triangle located on the toolbar. The button with the image of a green triangle with a beetle performs the functions of launching debugging mode. In this case, if breakpoints are set in the project, then when they are reached, the execution of the running application will stop and the line at which the break was made will be highlighted in the debugging editor.

QtCreator is noticeably different in design from other development environments. However, its design is surprisingly ergonomic. Among other things, in the era of wide screens, the toolbar located on the left in the main window of the development environment looks very advantageous. At the bottom of the toolbar, as already mentioned, there are buttons for launching the application, and at the top there are buttons for selecting tabs for the main window of the development environment. Let's look at the list of main tabs.

  • "Welcome" — Project selection
  • "Edit" — Editing the program.
  • "Debug" - Project debugging. Includes the necessary windows for monitoring objects.
  • "Projects" — Settings for projects loaded into the development environment. You should carefully study the options presented on this tab.
  • "Analyze" - Analysis of projects using special tools for detecting performance bottlenecks and memory leak problems.
  • "Help" Integrated help window. You may prefer working with the standalone help application, QtAssistant.

A simple example of placing widgets in an application window

Let's take the project that we created in the previous section using the QtCreator development environment wizard. The created project includes the following files.

  • app1.pro- project file
  • main.cpp widget.h and widget.cpp./li>
  • widget.h— interface of the main application window class.
  • widget.cpp— implementation of the main application window class.

The file names in your project may be slightly different. This could be either because you explicitly specified them elsewhere when creating the project, or the default values ​​for your version of QtCreator are different.

Let's open the implementation file of the main application window - widget.cpp. Let's change it to the state presented in the following example. Please remember that line numbers are provided for convenience of commentary only.

01. #include 02. #include 03. #include 04. 05. #include "widget.h" 06. 07. Widget::Widget(QWidget *parent) 08. : QWidget(parent) 09. ( 10. setWindowTitle(tr("Hello world!!!")); 11. setMinimumSize(200, 80); 12. 13. QLabel * plb = new QLabel(tr("Test"), this); QLineEdit * ple = new QLineEdit(this); 17. ple->setGeometry(110, 20, 80, 24); 18. 19. QPushButton * ppb = new QPushButton(tr("Ok"), this); ->setGeometry(20, 50, 80, 24); 21. ) 22. 23. Widget::~Widget() 24. ( 25. 26. )

Lines 01-03 include files with interfaces for the following widget classes.

  1. QLabel— label class. Often used to place static text information. Understands some HTML tags for formatting. Can be used to statically place an image. For example, from a file with a picture. Inherited from QFrame, so it can be adjusted to different edging shapes (borders).
  2. QLineEdit— a class for creating one-line text information input fields.
  3. QPushButton— button class. Most often used for signal processing clicked()- click on the button.

Class constructor body Widget contains two lines for setting window attributes (lines 10-11) and 8 lines for creating and placing three other widgets on the window field (lines 13-20).

Setting window attributes consists of the command to set the name of the application window and the minimum size of the application window. To set the minimum size, a method is used that takes the width and height of the window in pixels.

Line 13 contains the creation of an instance of the QLabel class. An object is created dynamically using the new operator. To create an object, a constructor is used, the first parameter of which specifies the string that the created object should represent. The second parameter of this constructor should specify the address of the object that will become the owner of the created label object. The owner's address is set to this. According to the rules of the C++ language, this is a pointer to the object within which it is used. That is, in this context, it is a pointer to the created instance of the class Widget. Thus, line 13 creates a label class object that should represent the specified text and whose owner is assigned to the current object.

Now it's time to talk about ownership chains, which are implemented in the Qt class system to solve the problem of destroying objects to prevent accidental memory leaks. It should be remembered that objects created dynamically, i.e. using the operator new, are located in a special memory area called heap and which live on the heap until they are explicitly destroyed by the operator delete. If the programmer does not monitor the destruction of objects that have become unnecessary and does not call the operator to destroy them delete, then this becomes the cause of a memory leak in the application, which is a serious problem for a number of programming languages, which include the C++ language.

There are several well-known schemes for automatically tracking the destruction of dynamically created objects. One of them is to use smart pointers, which should be discussed later. Another way is to create chains of ownership, which we will discuss now. The third way is to create a garbage collection subsystem, which should track unnecessary objects and destroy them. The latter method, traditional for the kernels of many modern languages, is practically not used in C++. The first two methods are much more popular in the traditions of the C++ language.

So, ownership chains implement the following simple idea. An object is created, the destruction of which we undertake to monitor. The easiest way is to create such an object by static definition and then it will be destroyed automatically when program execution reaches the end of the statement block (...) in which it was defined. Next, when dynamically creating other objects, we will assign owner objects to them. The owners' responsibilities will include the destruction of owned objects in the body of their own destructor. Recall that a destructor is a special method that is called when an object is destroyed. Thus, it is possible to build such an ownership chain relative to the first object, all elements of which will be automatically destroyed when the first object is destroyed. When organizing such a scheme, you only need to correctly take into account the lifetime of an object that is designated as the owner of another object, so that the objects are not destroyed prematurely.

This is exactly the ownership scheme implemented in the Qt class system. When creating many classes from this library, you can use a constructor whose only or last parameter takes a pointer to an object that is assigned as the owner to the object being created. This parameter is described as a parameter with a default value, which is defined as zero. Thus, if the owner's address is not specified, then the parameter is set to zero and the ownership scheme for such an object is disabled. In this case, you should remember to explicitly destroy such an object.

When implementing ownership circuit diagrams, some libraries use a parameter called owner, which translates from English as owner. However, in the Qt library this parameter is called parent, which translates from English as parent. As a result, some newbies have a misunderstanding due to the fact that the concept of “parent” traditionally refers to inheritance chains in OOP, but inheritance chains and ownership chains have nothing in common. Be careful and do not fall victim to misconceptions in this matter.

Let's return once again to line 13. There we created an object whose owner is assigned to the current object of the main application window. Variable plb, which stores the address of the created object, will be destroyed automatically when the end of the constructor code is reached. However, the object that was allocated in memory will continue to live, and will live until the object of the main application window is destroyed. Destroying the main window object will automatically destroy all objects that the window object owns.

On line 14, we access a method for setting geometry attributes that determine the placement of the custom object relative to its owner. The first and second values ​​indicate the horizontal and vertical coordinates for the upper left corner of the object. The third and fourth values ​​indicate the width and height of the custom object.

If you have ensured that the example created in the previous section assembled and ran without errors, then this example, which is an extension of the previous one, should also run.

Using this application, you can experiment with the application launch options. The easiest way to do this is in the console. Go to the application build directory and follow the following options to run the application with parameters. In each of the launches there should be a noticeable difference in the style of drawing widgets.

$ ./app1 -style=motif $ ./app1 -style=windows $ ./app1 -style=platinum

In this example, the application executable file is specified by the name app1. It is possible that in your case the executable file has a different name. In the Windows operating system, executable files have the extension exe. In addition, in the Windows operating system, you can launch an executable file from the current directory without specifying a relative path, i.e. without indication ( ./ ) - the dot character is a synonym for the current directory, and the forward slash character is a separator character in the file path entry. Also, keep in mind that the dollar symbol is the standard prompt symbol in the *nix console for a regular user and does not need to be typed as part of the command. In the Windows console, the prompt character is usually the angle bracket character ( > ).

Launch options can also be specified when launching an application from the QtCreator development environment. To do this, click on the icon on the left toolbar Projects. The corresponding settings tab will open. At the top of the window you can see a hierarchical system of tabs. The top-level tabs define the project, since multiple projects can be open in the development environment. The next level of tabs must, among other things, contain a tab Build&Run, which we need. In this tab, you then select the Qt SDK version, in case you are building a project for several versions at once. If you are assembling a project for one version, then the selection will consist of one element. Inside the Qt SDK version selection widget, there are two stylized buttons with rounded edges - buttons Build And Run. Click the button Run to select the appropriate group of settings. There, in the parameter group of the same name Run you will find a one-line input field opposite the label Arguments. This is the ultimate goal of our choice. Let's write the following line there.

Style=motif

Launch the application. Then try other values: windows And platinum. Recall that the class object QApplication supports a list of a couple of dozen launch parameters, which can be read about in the help for the corresponding class constructors.

As you work through the example, review the reference information for the classes used in the example. Try adding other instances of the label, single-line input field, and button classes to the form. In addition, try reading the help and adding objects of the following classes to the form.

  1. QComboBox— drop-down list class.
  2. QCheckBox— flag (checker) class.
  3. QTextEdit— class of a multiline input field. Used for both editing and presenting text. Contains very rich capabilities for presenting documents by separating the functions of special document composers into separate classes.

In conclusion of the lesson, it should be noted that the used method of “rigid” placement of objects on the form field, through explicit indication of the placement geometry, is not traditional and recommended in the Qt class library. The following lessons will look at layout managers, which are modern and convenient means of placing widgets on a form.

This is a cross-platform software development toolkit in the C++ programming language. There are also “bindings” to many other programming languages: Python - PyQt, Ruby - QtRuby, Java - Qt Jambi, PHP - PHP-Qt and others.
Allows you to run software written with its help on most modern operating systems by simply compiling the program for each OS without changing the source code. Includes all the basic classes that may be required when developing application software, ranging from graphical interface elements to classes for working with the network, databases and XML. Qt is fully object-oriented, easily extensible, and supports component-based programming techniques.
In this article I will show you how to write a simple “Hello, World!” program. using Qt4 library

Development environment

First, let's define the development environment. Personally, I use the cross-platform IDE Code::Blocks to write a program (you can read more about working in this IDE with Qt4). There are also plugins for working with Qt in Eclipse. A commercial version of Qt for MS Windows can be integrated into MSVS. Programs can also be written in any text editor, and then compiled from the command line.
For clarity, I will show how to compile programs written in Qt manually.

First program

First, create a file in any text editor and name it, for example, main.cpp
Let's write the following in it:
  1. #include
  2. #include
  3. QApplication app(argc, argv);
  4. QDialog *dialog = new QDialog;
  5. QLabel *label = new QLabel(dialog);
  6. label->setText( "Hello, World!" );
  7. dialog->show();
  8. return app.exec();

In lines 1 and 2 we included the Qt header files in which the main classes are located.
In line 4 we declared the main function - the main function from which the execution of any program begins. It returns an integer (the result of the program; 0 - if everything is in order) and takes two variables as input - the number of command line parameters and the array in which they are stored.
On line 5 we create an application object. We pass command line variables to this object.
On line 6 we create a dialog - a rectangular shaped graphical window with a title bar and buttons in the top right corner. Create a label (line 7). When we create a label, we pass a pointer to the dialog to its constructor, which becomes its parent. When you delete a parent, all its children are automatically deleted, which is very convenient. Then we set the label's text by calling the setText() function (line 8). As you can see from the example, you can use html tags for the displayed text.
On line 9 we display our label dialog box on the screen.
Finally, on line 10, we start the application's operating system event loop. We return the result of the object's operation as the result of the program.

Compilation

Now let's compile the written program.
Let's go to the directory where we saved our main.cpp file and run the command

$ qmake -project

This will create a Qt4 project template, which will automatically include all source code files located in this directory. The result will be a file with the same name as the current directory and the extension .pro. It will look like this:

TEMPLATE=app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

#Input
SOURCES += main.cpp

As a result, we will get a Makefile, which we use to compile the program by running the following command:

Let's wait until the compilation process ends and run our first program. It will look something like this:

Second program

To gain full control over the created windows and other widgets, you need to create classes derived from them. Let's create a derived class MyDialog. We will use the QDialog class as the parent class. We will place the description of our class in the header file mydialog.h:
  1. #include
  2. #include
  3. #include
  4. #include
  5. class MyDialog: public QDialog (
  6. Q_OBJECT
  7. public:
  8. MyDialog(QWidget *parent = 0);
* This source code was highlighted with Source Code Highlighter.
In the first four lines we include the necessary header files of the graphic elements used - the dialog, button, label and vertical layout manager. Use such large header files as , etc. in large projects is not recommended, as it increases compilation time.
On line six, we defined our class to derive from QDialog.
On the next line we specified the Q_OBJECT macro, which tells the Qt preprocessor that this class will use additional Qt features, for example, the signal and slot system.
On line 9 we specify the constructor for our dialog box. It has only one input parameter - a pointer to the parent object (0 if there is no parent).
We will define the constructor of our class in the mydialog.cpp file:
  1. #include "mydialog.h"
  2. MyDialog::MyDialog(QWidget *parent) : QDialog(parent) (
  3. QVBoxLayout *layout = new QVBoxLayout(this );
  4. QLabel *label = new QLabel(this );
  5. label->setText( "Hello, World!" );
  6. QPushButton *button = new QPushButton(this );
  7. button->setText("Close" );
  8. layout->addWidget(label);
  9. layout->addWidget(button);
  10. connect(button, SIGNAL(clicked()), this , SLOT(close()));
* This source code was highlighted with Source Code Highlighter.

On line 4 we create a layout manager that will automatically display all widgets added to it vertically. Creating an inscription is similar to the previous example.
In lines 7 and 8 we create a button and set its text. On the next two lines we add our widgets to the layout manager so that it will automatically arrange them.
On line 11, we connect the clicked() signal of the button to the close() slot of our dialog box. Each Qt object can have its own signals and slots, which can be connected to the signals and slots of other objects and thus communicate between program elements.
The main.cpp file will look like this:
  1. #include
  2. #include "mydialog.h"
  3. int main(int argc, char * argv) (
  4. QApplication app(argc, argv);
  5. MyDialog *dialog = new MyDialog;
  6. dialog->show();
  7. return app.exec();
* This source code was highlighted with Source Code Highlighter.

Rebuilding the project as a team

$ qmake -project

So that new files are automatically added to it and we compile it. This is what our new program looks like:

Third program

If a dialog box contains a lot of graphic elements, then creating such windows can be quite tedious. To simplify this process, there is a tool called Qt Designer. Let's launch it

And choose to create a dialog box without buttons. We add a label and a button to it and edit their text. Using the Signal/Slot Editor tool, we connect the clicked() signal of the button to the close() slot of the dialog box. We arrange them vertically using the layout manager. Save the resulting file under the name mydialog.ui. Later it will be automatically converted into a header file named ui_mydialog.h.
We change the header file of our dialog box mydialog.h as follows:

This is a cross-platform software development toolkit in the C++ programming language. There are also “bindings” to many other programming languages: Python - PyQt, Ruby - QtRuby, Java - Qt Jambi, PHP - PHP-Qt and others.
Allows you to run software written with its help on most modern operating systems by simply compiling the program for each OS without changing the source code. Includes all the basic classes that may be required when developing application software, ranging from graphical interface elements to classes for working with the network, databases and XML. Qt is fully object-oriented, easily extensible, and supports component-based programming techniques.
In this article I will show you how to write a simple “Hello, World!” program. using Qt4 library

Development environment

First, let's define the development environment. Personally, I use the cross-platform IDE Code::Blocks to write a program (you can read more about working in this IDE with Qt4). There are also plugins for working with Qt in Eclipse. A commercial version of Qt for MS Windows can be integrated into MSVS. Programs can also be written in any text editor, and then compiled from the command line.
For clarity, I will show how to compile programs written in Qt manually.

First program

First, create a file in any text editor and name it, for example, main.cpp
Let's write the following in it:
  1. #include
  2. #include
  3. QApplication app(argc, argv);
  4. QDialog *dialog = new QDialog;
  5. QLabel *label = new QLabel(dialog);
  6. label->setText( "Hello, World!" );
  7. dialog->show();
  8. return app.exec();

In lines 1 and 2 we included the Qt header files in which the main classes are located.
In line 4 we declared the main function - the main function from which the execution of any program begins. It returns an integer (the result of the program; 0 - if everything is in order) and takes two variables as input - the number of command line parameters and the array in which they are stored.
On line 5 we create an application object. We pass command line variables to this object.
On line 6 we create a dialog - a rectangular shaped graphical window with a title bar and buttons in the top right corner. Create a label (line 7). When we create a label, we pass a pointer to the dialog to its constructor, which becomes its parent. When you delete a parent, all its children are automatically deleted, which is very convenient. Then we set the label's text by calling the setText() function (line 8). As you can see from the example, you can use html tags for the displayed text.
On line 9 we display our label dialog box on the screen.
Finally, on line 10, we start the application's operating system event loop. We return the result of the object's operation as the result of the program.

Compilation

Now let's compile the written program.
Let's go to the directory where we saved our main.cpp file and run the command

$ qmake -project

This will create a Qt4 project template, which will automatically include all source code files located in this directory. The result will be a file with the same name as the current directory and the extension .pro. It will look like this:

TEMPLATE=app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

#Input
SOURCES += main.cpp

As a result, we will get a Makefile, which we use to compile the program by running the following command:

Let's wait until the compilation process ends and run our first program. It will look something like this:

Second program

To gain full control over the created windows and other widgets, you need to create classes derived from them. Let's create a derived class MyDialog. We will use the QDialog class as the parent class. We will place the description of our class in the header file mydialog.h:
  1. #include
  2. #include
  3. #include
  4. #include
  5. class MyDialog: public QDialog (
  6. Q_OBJECT
  7. public:
  8. MyDialog(QWidget *parent = 0);
* This source code was highlighted with Source Code Highlighter.
In the first four lines we include the necessary header files of the graphic elements used - the dialog, button, label and vertical layout manager. Use such large header files as , etc. in large projects is not recommended, as it increases compilation time.
On line six, we defined our class to derive from QDialog.
On the next line we specified the Q_OBJECT macro, which tells the Qt preprocessor that this class will use additional Qt features, for example, the signal and slot system.
On line 9 we specify the constructor for our dialog box. It has only one input parameter - a pointer to the parent object (0 if there is no parent).
We will define the constructor of our class in the mydialog.cpp file:
  1. #include "mydialog.h"
  2. MyDialog::MyDialog(QWidget *parent) : QDialog(parent) (
  3. QVBoxLayout *layout = new QVBoxLayout(this );
  4. QLabel *label = new QLabel(this );
  5. label->setText( "Hello, World!" );
  6. QPushButton *button = new QPushButton(this );
  7. button->setText("Close" );
  8. layout->addWidget(label);
  9. layout->addWidget(button);
  10. connect(button, SIGNAL(clicked()), this , SLOT(close()));
* This source code was highlighted with Source Code Highlighter.

On line 4 we create a layout manager that will automatically display all widgets added to it vertically. Creating an inscription is similar to the previous example.
In lines 7 and 8 we create a button and set its text. On the next two lines we add our widgets to the layout manager so that it will automatically arrange them.
On line 11, we connect the clicked() signal of the button to the close() slot of our dialog box. Each Qt object can have its own signals and slots, which can be connected to the signals and slots of other objects and thus communicate between program elements.
The main.cpp file will look like this:
  1. #include
  2. #include "mydialog.h"
  3. int main(int argc, char * argv) (
  4. QApplication app(argc, argv);
  5. MyDialog *dialog = new MyDialog;
  6. dialog->show();
  7. return app.exec();
* This source code was highlighted with Source Code Highlighter.

Rebuilding the project as a team

$ qmake -project

So that new files are automatically added to it and we compile it. This is what our new program looks like:

Third program

If a dialog box contains a lot of graphic elements, then creating such windows can be quite tedious. To simplify this process, there is a tool called Qt Designer. Let's launch it

And choose to create a dialog box without buttons. We add a label and a button to it and edit their text. Using the Signal/Slot Editor tool, we connect the clicked() signal of the button to the close() slot of the dialog box. We arrange them vertically using the layout manager. Save the resulting file under the name mydialog.ui. Later it will be automatically converted into a header file named ui_mydialog.h.
We change the header file of our dialog box mydialog.h as follows:

Every year there are more and more operating systems, and therefore it is more and more difficult for developers to satisfy the needs of users. The three most popular computer platforms - Windows, Linux and Mac OS, as well as three mobile platforms - Android, iOS and Windows Mobile - continue to actively fight among themselves. This means that a high-quality application must work on all major platforms.

Cross-platform development helps to cope with this problem. One of the most popular cross-platform development environments - Qt Creator - will be discussed in this article. We will look at how to install and configure Qt Creator, as well as how to work in Qt Creator.

What is Qt Creator

Qt Creator (not so long ago called Greenhouse) is one of the most common cross-platform IDEs. Its advantages are convenience, speed of operation, and also freedom, since it is open source software. Languages ​​such as C, C++, QML are supported.

The program was written by a company called Trolltech, which fully fulfilled the purpose of creating the environment - working with the Qt graphics framework. A convenient graphical interface with support for Qt Widgets and QML, as well as a large number of supported compilers, allows you to quickly and conveniently create your own cross-platform application.

The main goal of this IDE is to provide the fastest cross-platform development using its own framework. Thanks to this, developers have an excellent opportunity not to write applications natively (i.e., separately for each platform), but to create a common code and, possibly, tailor it to the characteristics of the operating systems used.

Qt Creator also includes the Qt Designer utility, which allows you to customize the appearance of your application window by adding and dragging elements (similar to Windows Forms in Visual Studio). The build systems used are qmake, cmake and autotools.

Installing Qt Creator

So, it's time to look at how to install Qt Creator. If for Windows the developers took care and created an offline installer, then in Linux 32-bit this feature is not provided. Therefore, during installation you may need a stable Internet connection (~20-30 minutes). First, download the installer:

  • Download Qt Creator for Linux 32-bit (click " View other options").
  • Download Qt Creator for Linux 64-bit.

After the download is complete, go to the folder with the file, right-click and select "Properties".

Now let's go to the tab "Rights" and check the box "Allow this file to run as a program".

Let's launch the program.

Now we press "Next".

Here you need to select an existing account or create one. This action is necessary to verify the license (commercial or non-commercial).

Click "Next".

Select the directory in which Qt will be located. It is important that there are no Cyrillic characters or spaces in the path!

This menu contains a selection of components. For example, you can choose to install tools for development on Android, or source components (this is needed for static assembly, if anyone needs this, write in the comments, and I will write a separate article). If you are not sure whether you need these components or not, leave them like this for now - even after installing Qt, it will be possible to remove and add elements.

In this window we accept the license. Click "Next".

If you are ready, begin the installation. You will be prompted for your superuser password (sudo), after which the downloading and extraction of files will begin. An alternative method is installation via a terminal. First you need to update the list of packages.

Download and install Qt:

sudo apt install qt5-default

Now install Qt Creator:

sudo apt install qtcreator

And, if necessary, the sources.

sudo apt install qtbase5-examples qtdeclarative5-examples

Setting up Qt Creator

After installation is complete, restart your computer and launch Qt Creator. Go to menu "Tools" -> "Options".

There are several tabs to consider here.

1. Wednesday- this is customizing the appearance of the IDE itself, as well as changing keyboard shortcuts and managing external utilities.

2. Text editor- here you can customize the appearance, fonts and colors of the editor.

3. C++- syntax highlighting, working with file extensions and UI (i.e. forms).

4.Android- paths to the necessary tools are collected here, and connected or virtual devices are also configured in this menu.

Installing Qt Creator components

If it suddenly happens that you forgot to install a component, or, conversely, want to remove it, then the Qt Maintenance Tool will come to the rescue. This is a tool that allows you to manage all components of Qt Creator.

To launch it, go to the applications menu, select "Development" -> "Qt Maintenance Tool".

Select the required option (Remove/add components, update components or remove Qt). Then perform the necessary operations and close the window.

Working with Qt Creator - first project

Well, the hour has struck! The installation of Qt Creator is complete. It's time to make your first cross-platform application on Linux and then compile it on Windows. Let it be... a program that displays a Qt icon, a button and an inscription, on which a random phrase will be displayed when the button is pressed. The project is simple, and, of course, cross-platform!

First, let's open the development environment. Let's click "File" -> "Create a file or project...". Let's choose the Qt Widgets application - it's quick and convenient to create. And its name is "Cross-Platform". That's how it is!

Set - default. We also leave the main window unchanged. Let's create a project.

First you need to configure the form - the main window of the application. It's empty by default, but it won't stay that way for long.

Let's go to the folder "Forms" -> "mainwindow.ui". The Qt Designer window will open:

Remove the menu bar and toolbar from the form by right-clicking and selecting the appropriate item. Now we drag the Graphics View, Push Button and Label elements like this:

To change the text, double-click on the element. In the Label properties (on the right), select the text position vertically and horizontally - vertical.

Now it's time to figure out the output of the icon. Let's go to the editor, right-click on any folder on the left and select "Add new...". Now we press "Qt" -> "Qt Resource File". Name - res. In the window that opens, click "Add" -> "Add prefix", and after adding - "Add files". Select the file, and in the window that appears "Incorrect file location" click "Copy".

It worked! We save everything. Open the form again. Right-click on Graphics View and select "styleSheet..." -> "Add resource" -> "background-image". In the left part of the window that appears, select prefix1, and in the right - our picture. Click "OK". Adjust the length and width.

All! Now you can start coding. Right-clicking on the button opens a context menu, now you need to click "Go to slot..." -> "clicked()". In the window we enter the following code:

Or you can download the full project on GitHub. Work with Qt Creator is completed, click on the green arrow icon on the left, and wait for the program to launch (if the arrow is gray, first click on the hammer icon). It started! Hooray!

A novice programmer constantly doubts which technologies to start mastering, this or any other. Should a beginner programmer learn Qt? Definitely necessary! For example, read this post or search for something on the Internet. Still not sure if you need Qt? If you write in C++, you should know Qt; you simply have no other alternative.

So, let's go...

Let's, for example, write a simple calculator - adding two numbers.

Let's create a new project. As we can see, there are several types of applications. We, as beginners, select "Qt Widgets Application":

We indicate the name of the project and the folder to place the files, for me: C:\projects\qt

Qt automatically generates the following files:

  • lesson1.pro - project file
  • main.cpp - main file with the main() function
  • mainwindow.cpp - source code of the main window
  • mainwindow.h - main window header file
  • mainwindow.ui - main window form file

Click the "Finish" button - the editor for developing programs in Qt opens.

For now, everything should be clear for a novice Qt developer...

Open the main form (to do this, go to mainwindow.ui).

On the left are the components for creating a screen form, on the right is the form itself, it is empty. Let’s add the necessary components, and don’t forget to name the QLineEdit input fields like this: edtA, edtB and edtC, respectively.

We see the input fields on the screen, their captions on the left and the “A + B =” button. When we click on this button we must add A and B and place the result in C.

What should I do? Any novice Qt developer will assume that you need to attach a button click handler to the button, and he will be right! In any other frameworks there is such a thing as event. But Qt decided to show off and came up with signals/slots. Although, in essence, this is practically the same thing.

Right-click on the “A + B =” button, a pop-up menu opens:

Click on "Go to slot"

Select the clicked() signal, and in the code editor that opens, write a small code in Qt:

Void MainWindow::on_btnOK_clicked() ( int a = ui->edtA->text().toInt(); // Take the text edtA and convert it to a number a int b = ui->edtB->text().toInt (); // Take the text edtB and convert it into a number b int c = a + b; // Add the numbers QString s = QString::number(c); // Convert the result to a string ui->edtC->setText (s); // Print the result in edtC )

The clicked() signal handling function is called the on_btnOK_clicked() slot.



Any questions?

Report a typo

Text that will be sent to our editors: