Using c libraries in qt. Why I love Qt and you should all love it too. Lecture and Lab

Naturally, I'm a writer like a hammer out of a bottle, so forgive me if you see excerpts from any familiar to you, don't blame me :-)))
And many thanks to uj for the help in the development of the article !!! Respect: - =))
And so ... let's go! ...

1. What is QT?
=================
Qt is a cross-platform library that aims to push native APIs out of your
programs. Qt is now a huge object-oriented harvester, in most cases
allowing to do without involving any other libraries.
First and foremost, Qt is a great tool for creating graphical user
interface (GUI). Qt includes a designer that makes it easy to create graphical interfaces
for your application.
You don't have to worry about writing build files for each platform, Qt will do it for you.
It is enough just to write a project file, in which to add all the files used, and the file
assemblies can be created with one call to the qmake utility (naturally, under the control of the target
platforms). On my own I will add that sometimes this file has to be edited by hand (but of course).
The significance of this library is evidenced at least by the fact that it is used in such successful projects,
like Borland C ++ Builder 6 and Opera.

2. Where to get it?
================
The library is supplied under several licenses, some of which are paid, others are not. Under
the X11 windowing system is always available from www.trolltech.com legally
take the GPL version of Qt (and use, of course, only
in non-commercial projects). Windows is trickier because, according to the top
TrollTech, this system is not an open source development arena. The last free version for
Windows - 2.3.0. But for resourceful people this is not a problem, there is an eDonkey network ;-) Current
moment is version 3.3.1. Version 4 is expected soon.

3. Technical details
=============================
Initially, Qt "worked" on user interface... And that is why this part of the library is the most
used and most developed. An interesting approach to positioning widgets (widget - element
GUI, everything that is drawn on the window, including itself) - the layer system (layout) allows you to forget about absolute positioning, like about a nightmare. Now the Layout class itself monitors what you do with, for example, the main window and positions all internal widgets following the change in the geometry of this window.
The central idea behind Qt is the signal-slot mechanism, which implements the relationship between objects.
This mechanism is implemented through precompilation, which allows you to use it without any
tweaks (if you are interested in Qt, right in this moment forget about callbacks).
Every Qt object (not just callouts!) Can generate some signals, hardcoded
hardwired into the structure of its class. Signal is a function declared in the signals special section.
and has no implementation ("body") but only passed arguments. Slots can be connected to the signal of an object (note, not a class). A slot is just a method, also declared in the special "slots" sections. Slots
can be accessible (section "public slots"), protected ("protected slots") and
hidden ("private slots"). Using the special connect method, the slot is connected to the signal.
A little example:

Connect (myValueDetector, SIGNAL (ValueChange (Value a),
myApplicationUpdater, SLOT (onValueChange (Value a))));

Then, each time the ValueChange signal is "emitted" by the myValueDetector object
the onValueChange slot of myApplicationUpdater will be called.
Pros - several slots can be connected to one signal.
Cons - one slot cannot be used for several signals (for example, for processing a group of buttons). Compare this with the VCL / CLX event system - it's just the opposite. Let's consider a small example of using the signal-slot mechanism:

As you can see, the code is "slightly" different from standard C ++. This text is fed to the input of the moc meta-compiler, which from it already produces standard C ++ code, which is then compiled by any compiler. Moc distinguishes "its", i.e. supporting signal-slot mechanism, classes from standard to keyword Q_OBJECT at the very beginning of the class declaration.

Let's list the main advantages of the Qt library core:
* native support for Unicode and localization (very well and very well implemented, dare I
notice). Qt4 promises a new font rendering engine that supports Unicode.
* powerful events and event filters (an event is something like a universal signal that can be sent to any widget, recognized and appropriately processed using filters. For example, pressing various keys)
* multifunctional interval controlled timers that make it easy and fast
insert many different jobs into an event-driven GUI.
* hierarchical and customizable object trees, organizing the belonging of objects to natural
way.
* guarded pointers QGuardedPtr, which are automatically NULL when
destruction of the corresponding object, in contrast to the usual pointers in C ++, which in this
case become "undefined pointers".
* Convenient documentation, available in Russian (unfortunately, I don’t know the links, but I can send them with pleasure upon request).

The core of the library includes both classes for building a GUI (for example: a label, an input field, a button and
etc.), as well as classes intended for organizing various data storage structures (for example,
list), working with files, networking and much more. Some of them
capabilities are implemented in the form of additional modules:
* Canvas module, a powerful tool for working with 2D graphics. It uses the principle
structuring graphics, which will undoubtedly be useful in programming simple two-dimensional
games and things like that. The canvas consists of several "elements", each element is represented
object. A number of interesting opportunities, such as collision-detection, moving (not in free versions under Windows: - ((()
objects with certain speeds along the axes. Read more at the link:
Link
* Network module, which provides network support in applications.
* OpenGL module that allows you to work with three-dimensional graphics using a portable library
OpenGL. Supported since version 2.3.2.
* SQL module that implements access to databases from Qt applications. This module broken down into three levels:
user (interface elements), programmatic (abstract database access) and level
drivers.
* the Table module, which provides you with a grid for displaying table data. Net
is a very powerful and flexible interface, working with which is one convenience
* XML module using SAX2 interface and second level DOM implementation.

This is not a complete list of Qt features.

3. How to write a simple QT application?
=================================================
Let's write the main.cpp file with the following content:

Now let's write a project file for this case (simple.pro):

PROJECT = simple
TEMPLATE = app
CONFIG = qt warn_on debug
SOURCES = main.cpp
TARGET = simple

V command line let's dial:

qmake simple.pro

And now it's the turn of the make utility: the application is ready. Run it, observe the window with the button.

Introductory part: Qt is not only about elements graphical interface... This framework is an interconnected system. The affinity of Qt objects is achieved through inheritance from the QObject class. And the connections between them through the signal-slot system. This article will describe the main classes and useful features of this library. QObject This is the base class for all Qt objects. Any class that uses signals and slots inherits it. It provides the ability to connect objects to each other. It also provides useful functionality for this. Introducing this ...

First Qt program:

The first program in Qt: Qt is a powerful toolkit with many ways to bring a programmer's ideas to life. Let's start mastering it from the very first program. So, you have at your fingertips the QtCreator development environment with a compiler connected to it (for example, MinGW). In the development environment, select Other project-> Project with subdirectories. Title: cppstudio. Here, for convenience, we will store all applications taken from the site. Create a QWidget project here with the name lesson_1 and delete the files mainwindows.h, mainwindows.cpp, ...

Introduction - the Qt graphics library

Qt is a free, widely used C ++ graphics library. It contains many components to support not only graphics, but also networking, databases, etc. General information: From the beginning of use, the programmer receives an interconnected framework. This makes it possible to use only built-in classes when writing most of the program and almost completely abandon the connection with a specific OS. This approach realizes the independence and freedom of the developer. (There is no need to rewrite the program for several operating systems... Algorithm for Windows can be compiled in ...

tl; dr - Qt library for building cross-platform C ++ windowing applications.

Qt, as a project, originated from the desire of C ++ developers to have a convenient toolkit for developing graphical program interfaces (GUIs). If, for example, in Java for these purposes AWT comes out of the box, and in Python Tk, then in C ++ there was nothing like this. And not only with regard to the development of the GUI, but also classes for working with the network, multimedia and other very popular things. Which made the developers very annoyed. Well, since there is demand, then the supply was not long in coming. In 1995, the first release of the library was released. Since then, Qt has rapidly expanded beyond just interface development.

Therefore, Qt should be considered not so much a set of classes for creating a GUI, but rather as a complete class toolkit for all occasions. This set of everything (or almost everything) that an application programmer may need to create almost any application. The structure of the library is logically divided into components, there are a lot of them and with each new version Qt, there are more and more useful classes in them.

There are two main components - QtCore, which is the core of the library, and QtGui, which is the components of the graphical interface. As we will see later, the created project always has these two components with it (with the exception of console applications, in which QtCore plays a mandatory role).

Well, then, depending on the needs, the developers are free to use whatever their heart desires. QtNetwork to work with the network, write your own Torrent client. QtMultimedia to implement a video-audio player. QtWebEngine for embedding a full-fledged browser engine into your application. And much more.

It should also be noted that the declared cross-platform is really present. You can take your code developed on one system (Windows, MinGW) and compile it with the compiler of another system (Linux, GCC) and get a binary file that can run there without much hassle. As practice has shown, special troubles begin when the application becomes heavily hung with third-party libraries.

A nice bonus for web developers will be the ability to develop programs not only in C ++, but also in the QML language, which is very similar to JavaScript. This is a special branch of Qt development, focused on rapid prototyping and mobile application development.

And of course, one of the highlights of Qt is the Qt Creator development environment. A universal and very convenient development environment in Qt, not overloaded with unnecessary functionality,.

After 24 hours of post life, I began to notice a leak of karma, so I apologize in advance for the possibly inadmissible style of presentation in the article and subjectivity

Hello Habrahabr!

Recently, I could not help but pay attention to the popularity of the Qt topic on the hub, but nevertheless, in the comments, I continue to meet people who say frankly false and incomprehensible things. With this post I wanted to dispel a little misconceptions about Qt and tell why you should switch from your Java / Obj-C / .NET to soft and fluffy Qt.

Under the cut there will be a lot of impressions, subjectivity and my humble opinions about the most wonderful framework for application development. However, I will try to add interesting things so that my article acquires at least some technically useful meaning. I hope you have fun reading and enjoy it.

Here we go?

Veshch No. 1. C ++ API

It's no secret that Qt has a very convenient API, and more specifically, the qtbase module contains a sufficient number of classes for most everyday tasks ( Qt is more than a GUI framework lol). I already talked about STL container wrappers in my article three years ago -. Classes for working with strings, debug output, and much, much more are also included.

QString fruits = "apple, banana, orange, banana"; QStringList fruitsList = fruits.split (","); qDebug ()<< fruitsList; // выведет в консоль [ "apple", "banana", "orange", "banana" ] fruitsList.removeDuplicates(); fruits = fruitsList.join(", "); qDebug() << fruits; // выведет в консоль "apple, banana, orange"
It is worth saying that Qt also has modules for conveniently working with XML, databases ( with the integration of the delicious-delicious cutesh MVC system), OpenGL, audio / video work (Phonon), network programming, WebKit2. For a hospital, the tasks facing an average project - this kitchen is enough in 90% of cases, and problems rarely happen with modules.

Given my love for C ++, I am very, very happy with the cross-platform support for various non-trivial things Qt provides. A couple of times I had to sort out particularly incomprehensible moments, but this is what it is.

Veshch No. 2. Qt Quick

Qt Quick is a mega-savvy approach to building a graphical user interface. Using a JavaScript-like declarative QML (guess where it came from, lol), you can achieve high performance when prototyping the interface in applications any difficulties. And the funny thing is that with this course of affairs, even a designer who knows JavaScript syntax can handle interface prototyping... These would all be empty words if I had not shown you an example of functional code (more can be found on the Qt Project - tamts).

Import QtQuick 2.0 Rectangle (id: page width: 320; height: 480 color: "lightgray" Text (id: helloText text: "Hello world!" Y: 30 anchors.horizontalCenter: page.horizontalCenter font.pointSize: 24; font. bold: true) Grid (id: colorPicker x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4 rows: 2; columns: 3; spacing: 3 Cell (cellColor: "red"; onClicked: helloText.color = cellColor) Cell (cellColor: "green"; onClicked: helloText.color = cellColor) Cell (cellColor: "blue"; onClicked: helloText.color = cellColor) Cell (cellColor: "yellow"; onClicked: helloText.color = cellColor ) Cell (cellColor: "steelblue"; onClicked: helloText.color = cellColor) Cell (cellColor: "black"; onClicked: helloText.color = cellColor)))

The implementation of the Cell object is extremely trivial and is defined this way

import QtQuick 2.0 Item (id: container property alias cellColor: rectangle.color signal clicked (color cellColor) width: 40; height: 25 Rectangle (id: rectangle border.color: "white" anchors.fill: parent) MouseArea (anchors. fill: parent onClicked: container.clicked (container.cellColor)))

There is not a single line of C ++ in this code and it works fine. Good, isn't it? I even felt like a wizard from this - it's easier to go to the store for bread than to rivet an application like this. However, in complex applications one QML is missing and we are merging it with C ++. This was discussed in many articles of the Qt Software hub - for example,.

Veshch No. 3. Community

Well, here we come to a pleasant moment. Speaking about me, I have been working with Qt for a relatively short time - only 5 years. Qt holds annual events - Qt Developer Days and Qt Contributors "Summit. I was at each of them once, last year, and I really liked it - the level of preparation is high, and the impressions are great. I also had to communicate with Qt" veterans " - people who have attended the summit for 10 years.I can imagine how cool it is to see the growth of such a project before our very eyes and to be at the epicenter of the entire development - just delicious.

These people are very tolerant of newcomers and treat them well, it was very easy and pleasant for me to make contacts with such wonderful people. The Qt Project has forums where everyone can get an answer to their question. It's funny, but it really is very lively and there really answer questions that arise in the process of learning Qt.

Veshch No. 4. Open source and code review

Sorets kyuta is openly developed mainly by Digia (com. Support +), KDAB, ICS and development enthusiasts. The whole thing is hosted on Gitorious - tadamts. To contribute to the development of the project, you need to go through strict code verification - automated (following the code style, which I already wrote about earlier -) and human - your code will be watched by bearded uncles who do not trust you and will look for backdoors in your code. All this is a rather complicated process (git / revision problems on the Review Board) and I will probably write an article about it the other day.

By the way, I have a couple of commits in the qtbase tree, so you can ask in ls - I'll try to answer the questions.

Veshch No. 5. Dynamics of project development

Qt has been in development for many years, since the late 90's. During this time, companies such as Trolltech and Nokia have already played enough of its commercial version, and now Digia is doing this. But one thing is for sure, the project is alive and well. For several years, everyone wrote the design on widgets (C ++ classes, all of them based on QWidget), and today even a small child can do it. I think it's not worth saying that in parallel with it, the most powerful thing is actively developing - Qt Creator, which today pleases not only Qt programmers!

^ cool Qt Creator, in which you can work wonders and you won't get anything for it.

Unfortunately, I do not have strict numbers, but they say that the code is optimized every day, and the codebase is carefully built up - new features are added and old bugs are fixed (I have already seen this many times). All this is very useful and cannot but rejoice.

In addition, platforms are being actively developed now. iOS, Android, Windows Phone, you can already build programs for them!

Outcome

I think you understand that Qt is really cool and after reading the article, you love it as much as I do.
Thank you for your attention!

Lecture and Lab

At the rate: OS

On the topic of: Qt programming environment

Completed:

Students of group А-06-09

Smirnov Andrey

Marugin Mikhail

1. Introduction

2.History

3. Development of the environment

4.Scope of application

5.General information

6.Components

7. Development environment

8.Working with Qt Creator

9 examples

10.Laboratory assignment

Introduction

There are also "bindings" to many other programming languages: Python - PyQt, Ruby - QtRuby, Java - Qt Jambi, PHP - PHP-Qt and others.

It allows you to run software written with it on most modern operating systems by simply compiling the program for each OS without changing the source code. Includes all the core classes that you might need in application software development, from GUI elements to networking, database, and XML classes. Qt is fully object-oriented, easily extensible, and supports component programming techniques.

Since version 4.5, Qt is distributed with various licenses. This means that if you are going to create commercial applications, you must purchase a commercial Qt license; if you are creating an open source program, you can use the GPL version.

Story

The Qt development tools first became public in May 1995. Qt was originally developed by Haarward Nord and Irik Chaimb-Ing.

In 1991, Haarvard began writing the classes that actually formed Qt, with design decisions made in collaboration with Ayric.

The next year, Ayric came up with the idea for "signals and slots," a simple yet powerful paradigm for GUI programming that is currently being adopted by several other tools.

By 1993, Haarvard and Eirik had developed the first graphics core, Qt, and could create their own widgets.

Uninteresting notes: The letter "Q" was chosen as the class prefix because it had a pretty face in the Emacs font that Haarvard used. The letter "t" has been added for "toolkit".

Development

In April 1995, the Norwegian company Metis signed a contract with them to develop software based on Qt.

May 26, 1995 - First public release of Qt. Qt could be used in both Windows and Unix development, and the programming interface was the same on both platforms.



From 1996 to 2001 - development to the Qt3 version. Qt now worked on Windows, Mac Os X, Unix systems.

Summer 2005 - Qt 4.0 released. With about 500 classes and over 9000 functions, Qt 4 is larger and richer than any previous version; it has been split into several libraries so that developers can only use the parts of Qt they need.

As of today, version Qt4.8

Qt 4 is a big improvement over previous versions; it contains a completely new set of efficient and easy-to-use container classes, improved model / view architects functionality, a fast and flexible 2D graphics framework and powerful classes for viewing and editing Unicode text, not to mention thousands of small improvements across the spectrum of classes Qt.

Qt 4 is the first version of Qt available on all supported platforms for both commercial and open source development.

Application area

Ability to create desktop applications for Windows, Linux, Mac OS X (both console and windowed graphical interface). In the past few years, there has been a trend towards an increase in the number of manufactured mobile devices. As a result, Qt was ported to mobile platforms: Symbian, Maemo, MeeGo. We also know about the successful experience of porting Qt Lighthouse to the Android platform.

General information

It allows you to run software written with it on most modern operating systems by simply compiling the program for each OS without changing the source code.

Includes all the core classes that you might need in application software development, from GUI elements to networking, database, and XML classes.

Qt is fully object-oriented, easily extensible, and supports component programming techniques.

There are versions of the library for Microsoft Windows, UNIX systems with the X11 graphics subsystem, iOS, Android, Mac OS X, Microsoft Windows CE, QNX, embedded Linux systems, and the S60 platform. The possibility of introducing Qt support in Windows Phone is currently being considered. Porting to Haiku is also in progress.

What distinguishes Qt from other libraries is the use of Meta Object Compiler (MOC)- a preliminary system for processing source code (in general, Qt is a library not for pure C ++, but for its special dialect, from which it "translates" MOC for subsequent compilation by any standard C ++ compiler). MOC allows you to multiply the power of libraries by introducing concepts such as slots and signals. It also makes your code more concise. The MOC utility searches the C ++ header files for class descriptions containing the Q_OBJECT macro, and creates an additional C ++ source file containing the meta-object code.

Qt allows you to create your own plugins and place them directly in the visual editor panel. It is also possible to expand the usual functionality of widgets related to their placement on the screen, display, redrawing when the window is resized.

Qt comes with a visual development environment for the graphical interface "Qt Designer", which allows you to create dialogs and forms in WYSIWYG mode.

Qt comes with "Qt Linguist" - a graphical utility that makes it easier to localize and translate a program into many languages; and "Qt Assistant", a Qt help system that makes it easy to work with the library's documentation, and also allows you to create cross-platform help for Qt-based software. Starting with version 4.5.0, the Qt kit includes the development environment "Qt Creator", which includes a code editor, help, graphical tools "Qt Designer" and the ability to debug applications. Qt Creator can use GCC or Microsoft VC ++ as the compiler and GDB as the debugger. For Windows versions, the library is completed with a compiler, MinGW header and object files.

Components(select a couple )

The library is divided into several modules, for the fourth version of the library these are:

QtCore- classes of the core of the library used by other modules;

QtGui- components of the graphical interface;

QtNetwork- a set of classes for network programming. Support for various high-level protocols may vary from version to version. In version 4.2.x there are classes for working with FTP and HTTP protocols. Classes such as QTcpServer, QTcpSocket for TCP and QUdpSocket for UDP are designed to work with TCP / IP protocols;

QtOpenGL- a set of classes for working with OpenGL;

QtSql- a set of classes for working with databases using the structured query language SQL. The main classes of this module in version 4.2.x: QSqlDatabase- a class to provide a connection to a database, to work with any specific database requires an object inherited from the QSqlDriver class - an abstract class that is implemented for a specific database and may require the database SDK to compile. For example, to build a driver for a FireBird / InterBase database requires .h files and static linking libraries included in the delivery set of this database;

QtScript- classes for working with Qt Scripts;

QtSvg- classes for displaying and working with data Scalable Vector Graphics (SVG);

QtXml- module for working with XML, supported by SAX and DOM models of work;

QtDesigner- classes for creating QtDesigner extensions for their own widgets;

QtUiTools- classes for processing Qt Designer forms in the application;

QtAssistant- reference system;

Qt3Support- a module with classes required for compatibility with the Qt library version 3.x.x;

QtTest- module for working with UNIT tests;

QtWebKit- WebKit module, integrated into Qt and available through its classes;

QtXmlPatterns- module to support XQuery 1.0 and XPath 2.0;

Phonon- a module to support playback and recording of video and audio, both locally and from devices and over the network;

QtCLucene- a module to support full-text search, used in the new version of Assistant in Qt 4.4;

ActiveQt- a module for working with ActiveX and COM technologies for Qt-developers under Windows.

QtDeclarative- a module providing a declarative framework for creating dynamic, customizable user interfaces.

The library uses its own project format, called a .pro file, which contains information about which files will be compiled, which paths to search for header files and much other information.

Subsequently, using the qmake utility, the makefiles for the compiler make utility are obtained from them. It is also possible to work with the help of integrators with Microsoft Visual Studio 2003/2005/2008/2010. More recently, integration into Eclipse has become available for the 4.x.x version of the library.

Java developers can use Qt using the Qt Jambi framework from the same vendor (Qt Software officially stopped developing this framework since 2009).

«+»

One of the great advantages of the Qt project is the availability of quality documentation. The documentation articles are provided with lots of examples. The source code of the library itself is well-formatted, well-commented and easy to read, which also makes learning Qt easier.

Development environment

Qt Creator is a cross-platform free IDE for C, C ++ and QML development. Developed by Trolltech (Nokia) to work with the Qt framework. Includes a graphical debugger interface and visual interface development tools using both QtWidgets and QML. Supported compilers: Gcc, Clang, MinGW, MSVC, Linux ICC, GCCE, RVCT, WINSCW.

The main goal of Qt Creator is to simplify application development using the Qt framework on different platforms. Therefore, among the features inherent in any development environment, there are also specific ones, such as debugging applications in QML and displaying data from Qt containers in the debugger, a built-in interface designer in both QML and QtWidgets.

Working in Qt Creator

Qt Creator has a handy wizard for creating new projects, forms, class files, and so on. Although, instead of creating a ui-file for the main window, it would be possible to insert some simple code into the project without touching the domain of visual programming. After creating or opening a project, the development environment itself appears before us. It looks strange at first. For example, there are no famous tabs (tabs with roots). Rather, they are for everything except the editor files. The files themselves are available from two lists: project files (by default on the left panel) and already open files (on the top line of the editor panel). Why did the decision to abandon tabs be made? I think it's for the sake of saving screen space.

Another unusual point is rather relative, since the "no dialogues" interface has long been adopted by some other programs (for example, the TEA editor). In Qt Creator, for searching and replacing by text, input fields appear, when typing in which the found matches are immediately highlighted in the editor. For search further there is F3, and for replacement - a separate input field. Options are also located nearby. Thanks to all this, such operations are carried out quickly and conveniently. The same applies to information and debug panels: no modality, unnecessary windows overlapping the main one, and other delights of the former approach to interface architecture. Everything in one main window!

Qt Creator also takes care of the code editor. Nowadays, you can hardly surprise anyone with syntax highlighting, so let's move on to other useful features. For example, there is a "full code parser" - this is the ability of the editor to check the code for correctness from the point of view of the programming language. When you type the code, you can see where you made a syntax error even before compiling. It works in most cases, although there are exceptions. Automatic completion works great: typed the name of the class instance, put a dot or "->" - and you get a drop-down list with class members. There is a folding of blocks of code - the so-called "folding". However, I think that the code is more descriptive without it, so I never use this opportunity.

Well done moving around the code - and without external ctags. It is enough to put the cursor on the name of the function or variable and press F2, after which the editor moves to the place of the declaration. Shift-F2 - toggles between declaration and code, and F4 - just toggle header and cpp file. If you move the mouse pointer to the name of the function called in the code, a hint on its parameters will appear.

The help system works as follows. Let's say you have a QMenu variable somewhere in your code. If you put the cursor on it and press F1, a help panel appears with a description of the QMenu class. Also in the main window there is a Help tab, where all the Qt documentation is available.

So, most of the time you will be spending in the editor tab. It is not entirely clear why there are as many as five sections in the Qt Creator settings for different editors - by default, for scripts, for C ++, for projects and Perforce (a commercial version control system). The C ++ editor settings are the code editor settings for your Qt program. Note that in the most recent snapshots of Qt Creator, the font settings are still sorted into a single section, which is to be expected.

It's useful to tinker with the lighting and font settings, since the default is not very convenient to work with. Firstly, the font size is too small, and secondly, the code blocks enclosed in #ifdef / #endif are interpreted by the parser as "disabled code" (an expression from the Qt Creator settings) and are grayed out - it is not very convenient to parse what has been written. If you don't like folding, turn off Display Folding Markers in the editor settings.

You can set bookmarks and breakpoints in the editor margins. The editor panel itself can be split into an infinite number of nested panels, much like Konqueror. Thus, on the screen, you can simultaneously edit either several files, or the same document, but in different places. To do this, you must first split the editor panel (for example, through Window - Split Top / Bottom), and then select the Window - Duplicate document menu item. This approach is sometimes more useful than tedious navigation through bookmarks.

Qt Creator's architecture is based on plugins. The editor is a plugin, the bookmark engine is a plugin, the panel with project files is also a plugin, and so on. The list of installed plugins can be found in the Help - About Plugins menu. Probably, in the future it will be possible to install additional plugins, but so far I have not found a mechanism for this, as well as additional plugins themselves. But in the assemblies themselves, new plugins appear at an unprecedented rate. Subversion and Git support modules appeared in just a month. Qt Creator is now inherently transient. Qt Creator menu items are renamed from version to version and carried over to other submenus. Not to mention, additional features are constantly being born.

Let's pay some attention to the settings window, of which, fortunately, there are many. You can customize keyboard shortcuts and, moreover, import / export them using external files. This is convenient for transferring your favorite keyboard shortcuts from machine to machine. Qt Creator comes with two such preinstalled files by default: for MS Visual C ++ and Xcode. Everything related to automatic completion, indentation, syntax highlighting, and more, is in the editor's settings - Text Editor.

Another interesting tool in Qt Creator is Locator (in older versions, Quick find). In order to move focus to it, just press Ctrl-K. Looks like a regular search bar, but serves to quickly search for anything in whatever you like. More specifically, it searches for files, in files, classes, functions. Supports modifier characters to refine the search task. For example, you might want to search the Qt documentation for a description of the qApp global pointer. What to do? Previously, you had to open the documentation through a browser and search there. But in Qt Creator, when Locator is always at hand, is it enough to type in the search bar? qapp and press Enter. Move to line 100? Please - dial the number and Enter again.

Finally, let's get back to interacting with the GDB debugger. Qt Creator through its graphical interface allows you to debug not only the current project, but also any external program - of course, if it is compiled with debugging information. When debugging, various kinds of data are displayed in separate tabs: threads, variables, breakpoints, and the disassembler. The QStringList instance looks especially clear in the debugger - all its elements are visible. The standard output of GDB itself is disabled by default, as are some other tabs, such as information about the contents of processor registers. If the program crashes for some reason, then according to the data in the debug panel, you can immediately see where the crash occurred in the code.

Example 1

Our first program will be with a graphical user interface (GUI).

#include

#include

int main (int argc, char * argv)

QApplication app (argc, argv);

QPushButton * newbtn = new QPushButton (QObject :: tr ("OK"));

QObject :: connect (newbtn, SIGNAL (clicked ()), & app, SLOT (quit ()));

newbtn-> resize (180,40);

newbtn-> show ();

return app.exec ();

The first two lines are the definitions of the Qt classes.

These classes belong to the Application Programming Interface (API) of the Qt library. The library contains files with the same names that describe this class.

Line 6 creates a QApplication object. This class manages all the resources of the application. Then an object of class QPushButton (button) is created with the inscription "OK".

The button is a widget. Line 8 binds the button's clicked () signal to the quit () slot of the QApplication3 object. On line 9 we set the size of the widget and on line 10 we display it. Line 11 transfers control of the Qt application. At this point, the program enters the loop for processing user and system events.

Example 2. Validating user input

When the user is prompted to enter any data in a text field, it is quite often possible to get something completely unexpected. The user can enter numbers in words, use the wrong decimal separator, or forget to enter the area code in the phone number. Thus, in most cases, it is necessary to check the correctness (admissibility) 1 of the specified information.

Qt contains the QValidator class to ensure that the input is correct. The data class cannot be used directly. To check the data, you will either have to use the ready-made subclasses QIntValidator, QDoubleValidator, QRegExpValidator, or write the subclass yourself.

The validate (QString & input, int & pos) method is passed a string for validation and the position of the cursor. The method can return the following values:

QValidator :: Invalid - The string is invalid.

QValidator :: Acceptable is a valid string.

QValidator :: Intermediate - The string cannot be accepted in its current state, but it can become valid.

Let's write a program that will check if a string is a real number. Let's use the ready-made QDoubleValidator class:

MainWindow :: MainWindow ()

grid = new QGridLayout; doubleedit = new QLineEdit;

lbdouble = new QLabel (tr ("Double:"));

lbresult = new QLabel (tr ("Result:"));

result = new QLabel;

vld = new QDoubleValidator (-5, 2999, 5, this);

vld-> setNotation (QDoubleValidator :: ScientificNotation);

doubleedit-> setValidator (vld);

grid-> addWidget (lbdouble, 0, 0);

grid-> addWidget (doubleedit, 0, 1);

grid-> addWidget (lbresult, 1, 0); grid-> addWidget (result, 1, 1);

resize (160, 120); setLayout (grid); ...

The constructor for the QDoubleValidator class can take the following parameters:

QDoubleValidator :: QDoubleValidator (double bottom, double top, int decimals, QObject * parent)

The range of real numbers is from bottom to top, inclusive. decimals - number of digits after decimal point2.

Using the setNotation (Notation) method of the QDoubleValidator class, you can set the scientific notation to be valid:

QDoubleValidator :: StandardNotation is standard notation (For example: 1.124 or -2).

QDoubleValidator :: ScientificNotation is scientific notation, i.e. the number can have an exponential part (For example: 2.7E-3 or 3.3E + 2)

To check the validity of the entered data, we will use the validate () method:

MainWindow :: MainWindow ()

QObject :: connect (doubleedit, SIGNAL (textChanged (const QString &)), this, SLOT (showresult (const QString &)));

void MainWindow :: showresult (const QString & text)

QString numtext = text;

if (vld-> validate (numtext, pos) == 0) result-> setText (tr ("invalid"));

if (vld-> validate (numtext, pos) == 1) result-> setText (tr ("Intermediate"));

if (vld-> validate (numtext, pos) == 2) result-> setText (tr ("Acceptable"));

Program code

main.cpp

#include

#include "mainwindow.h"

int main (int argv, char ** args)

QApplication app (argv, args);

MainWindow window;

return app.exec ();

Mainwindiw.h#ifndef MAINWINDOW_H # define MAINWINDOW_H #include class MainWindow: public QWidget (Q_OBJECT public: MainWindow (); private slots: void showresult (const QString &); private: QGridLayout * grid; QLineEdit * doubleedit; QLabel * lbdouble, * lbresult, * result; QDoubleValidator * vld;); #endif Mainwindow.cpp#include #include "mainwindow.h" MainWindow :: MainWindow () (grid = new QGridLayout; doubleedit = new QLineEdit; lbdouble = new QLabel (tr ("Double:")); lbresult = new QLabel (tr ("Result:") ); result = new QLabel; vld = new QDoubleValidator (-5, 2999, 5, this); vld-> setNotation (QDoubleValidator :: ScientificNotation); doubleedit-> setValidator (vld); grid-> addWidget (lbdouble, 0, 0); grid-> addWidget (doubleedit, 0, 1); grid-> addWidget (lbresult, 1, 0); grid-> addWidget (result, 1, 1); resize (160, 120); setLayout (grid) ; QObject :: connect (doubleedit, SIGNAL (textChanged (const QString &)), this, SLOT (showresult (const QString &)));) void MainWindow :: showresult (const QString & text) (int pos = 0; QString numtext = text; if (vld-> validate (numtext, pos) == 0) result-> setText (tr ("invalid")); if (vld-> validate (numtext, pos) == 1) result-> setText (tr ("Intermediate")); if (vld-> validate (numtext, pos) == 2) result-> setText (tr ("Acceptable"));)

Example 3. 2D graphics

Using the QPainter class, we can paint on any object inherited from the QPaintDevice class (QWidget, QPrinter, QImage, QGLFramebufferObject, etc.). You can draw geometric shapes, pixel maps, text. First, let's look at the classes that can be useful when working with QPainter.

The QPoint and QPointF classes are used to define the position of a point in a two-dimensional coordinate system. QPoint is for integers and QPointF is for real numbers. The operations of addition, subtraction, multiplication, division are applicable to points:

QPoint point (5, 5);

QPoint point2 (10, 10);

Also, points can be compared with each other and for the equality of their coordinates to zero.

QPoint point (5, 10);

QPoint point2 (5, 10);

if (point == point2)

bln = point.isNull ();

The QSize and QSizeF classes are used to store the size. In addition to methods similar to those of the QPoint and QPointF classes, these classes have a scale () method that allows you to scale a graphic object.

The QRect and QRectF classes are used to store rectangular areas (top-left coordinates and size):

QRectF (QPointF point, QSizeF size);

The QLine and QLineF classes describe a straight line. The QPolygon and QPolygonF classes describe a closed shape formed by straight lines.

Color information can be stored using the QColor class. The Qt environment supports 3 color models: RGB, CMYK, and HSV. For the RGB color model, there is a QRgb structure. There are several ways to set a color in an object of the QColor class:

Passing parameters to the constructor

unsigned int red = 50;

unsigned int green = 100;

unsigned int blue = 0;

unsigned int alpha = 128;

QColor mycolor (red, green, blue, alpha);

QRgb rgb1 = (50, 100, 0);

QColor mycolor2 (rgb1);

Using the methods QColor :: setRgb (), QColor :: setRgba (), QColor :: setRgbF (), QColor :: setHsv (), QColor :: setHsvF (), QColor :: setCmyk (), QColor :: setCmykF ( )

mycolor.setHsv (200, 100, 50);

It is possible to set a color in one model and read in another:

unsigned int h, s, v;

QColor mycolor (100, 100, 100);

mycolor.getHsv (& h, & s, & v);

Let's go back to the QPainter class. In order to start drawing, we just need to create an object of the QPainter class and pass it a pointer to an object for drawing:

QPainter pnt (this);

pnt.drawLine (line);

void Wnd :: paintEvent (QPaintEvent * event)

QLineF line (10.0, 80.0, 90.0, 20.0);

pnt.begin (this);

pnt.drawLine (line);

The QWidget :: paintEvent () method is called for widgets that need to be repainted.

In most cases, drawing is done with a single QPainter on multiple drawing objects. You can use the QPainter :: save () and QPainter :: restore () methods to save the old drawing settings (when switching to a new object). QPainter :: save () pushes onto the setup stack, and QPainter :: restore () pops.

To draw the outlines of the shape, you must pass the QPen object (pen) to the QPainter using QPainter :: setPen ().

Using the appropriate methods, you can set the style of the pen (color, thickness, appearance of line ends).

To fill closed paths, use a brush i.e. an object of the QBrush class. Similar to the QPen class, the brush is set using the QPainter :: setBrush () method. You can pass either a QBrush object or one of the predefined BrushStyle styles into it:

QPainter pnt (this);

pnt.setBrush (QBrush (Qt :: blue, Qt :: VerPattern)); // blue brush with vertical hatching

The QPainter class allows you to rotate, scale, offset, and bevel objects. There are corresponding methods for these operations: rotate (), scale (), translate (), sheap ().

The Qt library supports the Anti-Aliasing technique:

pnt.setRenderHint (QPainter :: antialiasing, true);


Top