The Book of qt4 (1.5 QT overview)
The Book of qt4 Translation
Qt programming Art
---------------------------------------------------------------------------------
Original Name: The Book of QT 4: The art of building QT applications
The Book of QT 4 Chinese version: QT programming Art
Zhang Xiaoke mcxiaoke@gmail.com
---------------------------------------------------------------------------------
Chapter 1 basics, tools and the first line of code
**************************************** ******************************
* ************************* 1.5 QT overview *********** ******************
**************************************** ******************************
In fact, QT is not only a huge library, but also 7 libraries. It also includes many tools, and qmake is one of them.
1.5.1 QT Library
Today, the term GUI toolkit represents more than just a small part of the GUI provided by the system ). In particular, QT contains many extension classes for application development. Many of these classes are related to the graphic interface of the program, but also involve network programming, OpenGL support, and XML development. A wide range of uses depend on the platform independence of the QT class: except for a few, all classes are available on all operating systems, and the same classes have the same method and behavior.
Qt4 contains the following libraries:
Qtcore contains basic classes without GUI interfaces.
Qtgui contains the GUI basic class.
Qtnetwork contains Network classes.
Qtopengl supports OpenGL.
Qtsql contains SQL database classes.
Qtxml contains XML and Dom classes. (See page 45th)
Qtassistantclient allows you to use the QT assistant as the document browser of your program.
Qt3support includes classes to ensure backward compatibility with qt3.
Qt 4.1 adds the qtsvg library, which provides support for the SVG vector graphics format. It also adds the qttest library, also known as qtestlib, including the unit test framework.
In the final version of QT 4.2, qutech added the qtsag module to support freeyuntop.org's Public Information System ).
You may need to connect program code to multiple library files. The most commonly used files are qtcore and qtgui. Therefore, qmake contains the two libraries by default.
The library file to be connected is specified by the qmake variable QT. The core and GUI variables are included by default. For example, to develop a graphic interface program with network support, you should add the value network to the QT variable. Add the following line to the project file. Pro:
Qt + = Network
To compile a console program that supports XML, you only need to link qtcore and qtxml without qtgui. Therefore, you must add the value XML and remove the value GUI. Add the following two lines to the project file:
Qt-= Gui
Qt + = xml
If you want to use all the library files in QT 4.0, write as follows:
Qt + = network OpenGL SQL XML support (core and GUI are included by default and do not need to be written)
In addition to being specified in project files, there is also a particularly useful topic on QT library knowledge. In addition to defining independent header files of a class (the names of these header files are the same as those described in the class), QT also provides header files for its library. Each of these files contains the interface descriptions of many class files in a library. Therefore, from the beginning of this book to all examples so far (we only use classes in qtgui), we did not write many single # include declarations, but simply wrote them like this:
# Include <qtgui>
However, the header files of these libraries are usually very long, significantly slowing down the compilation process. If the compiler supports precompiled header files, this is not a problem, but it is only supported by the latest Compiler (for example, gcc3.4 or a later version ).
Basic Library qtcore
Qtcore is an essential library for every Q program. It provides the following functions:
Basic data types, such as qstring and qbytearray
Basic data structures, such as qlist, qvector, and qhash
Input and Output classes, such as qiodevice, qtextstream, and qfile
Classes that support multi-thread programming (including qwaitcondition and qthread)
Basic class qobject and qcoreapplication (base class of qapplication class)
These classes do not depend on GUI components. Independent of the GUI, the QT program does not use the GUI (such as the console program ).
In a non-graphic interface program, qcoreapplication assumes the responsibility of qapplication in the graphic interface program: Responsible for event loops. If you need to use multi-thread asynchronous communication in the network connection, you will find this useful.
Graphical interface library qtgui
The qtgui library contains all class files required for graphic user interface programming:
Qwidget class and its subclass, such as qlabel and qpushbutton
Layout class (including qvboxlayout, qhboxlayout, and qgridlayout)
Class used to add menus to programs, such as qmainwindow and qmenu
The class used for plotting, such as qpainter, qpen, and qbrush.
Provides ready-made dialog box classes (including qfiledialog and qprintdialog)
Qapplication class
The qtgui library depends on the qtcore library.
Network Library qtnetwork
The qtnetwork Library provides some classes required for compiling network applications. In addition to supporting simple socket communication through qtcpsocket and qudpsocket, the network library also supports HTTP and FTP connections of CS (client-server) through qhttp and qftp.
Unlike qtgui, qtnetwork depends on the qtcore library, but it can also be used with qtgui and other libraries.
OpenGL supports library qtopengl
The qtopengl Library supports OpenGL in QT programs. It provides the qglwidget Class-a qt widget in which you can draw using OpenGL commands. Qtopengl depends on the qtcore and qtgui libraries.
Database-type qtsql
The qtsql Library provides the ability to access the SQL database in the QT program. This library contains classes used to establish SQL database connections and query and modify data. The SQL data supported by QT includes: open source databases PostgreSQL, MySQL, and SQLite. Qtsql depends on the qtcore library, which will be discussed in chapter 9.
XML library qtxml
The qtxml Library provides a simple, non-verified XML parser. It implements this function through the sax2 (Simple API for XML) interface.
Qtxml also contains an implementation of the DOM standard (Document Object Model. The corresponding class allows you to parse XML documents, manipulate the tree structure, publish modified documents in XML document format, or use Dom to create a new XML document.
This library depends on the qtcore library, which will be discussed in chapter 13th.
Qt3 compatible library qt3support
Compared with QT 3, QT 4 has a significant change: some class inclusion improvements are incompatible with QT 3, some classes are replaced by new classes with different names in QT 4. To simplify the process of porting QT 3 programs to QT 4, qt3support provides QT 3 classes in the qt3support library. However, you should not use this library in the new program because these classes have stopped development. Because this book describes QT 4 programming, we will not use these classes and will not discuss them later.
Vector Graphics Library qtsvg
The XML-based SVG vector graphics format released by W3C has great potential. Since QT 4.1, the qtsvg Library supports SVG standard SVG basic and SVG Tiny, which are used to display SVG files and animations. Although the qtsvg library cannot create them, you cannot manipulate SVG files as XML documents through the DOM tree.
Help library qtassistantclient
The QT Assistant Library allows you to precisely control the QT assistant application. Allow you to use it as an independent help file browser for your program platform. The core of this module is the qassistantclient class.
The custom Help Page used by QT assistant must be in the basic HTML format and an XML file must be used to describe the document structure.
Test Library qtestlib
Originally, qtestlib was provided to paying users outside of the QT core release version, and has been included in the QT general release version since QT 4.1.0. The Test Library contains tools used to write strict unit tests. The scope is similar to JUnit in Java.
Message library qtdbus
Qtdbus is a message protocol in Linux and Unix-like systems. For example, both the Linux Hardware Abstraction Layer (HAL) and the kde4 to be released use the Protocol as the inter-process communication protocol. Although the Windows and Mac OS X versions already exist, QT 4.2 will only provide the qtdbus library for UNIX systems. However, it may change in the future.
Activeqt and migration
The extended activeqt feature exclusive to Windows makes it possible to implement ActiveX components through QT and to use ActiveX Components in QT programs. However, this function is only available in the commercial version of QT.
Ququfun also provides a solution for migration from a program based on MFC, motif, and XT. However, like activeqt, they are provided only as a separate commercial plug-in for QT 4, so they will not be discussed in this book.
1.5.2 tools and utilities
In addition, QT contains three dialogs for displaying QT documents, creating WYSIWYG, and translating programs into other languages. The QT toolkit also provides a series of command line programs for completing multiple tasks.
Document Browser "QT assistant"
Qt documents contain simple HTML files, which can be viewed in a browser or QT assistant. Unlike the browser, the QT assistant displays the index of the entire document and allows full-text search of the document.
The keyword directory of the QT assistant is particularly useful when QT is used for daily work. For example, if you need a class document, such as qlabel, simply type qlabel In the homepage input box. After you press enter, you will immediately enter the perfect class document.
Qt assistant is an important supplement to this book because it not only explains the newly added API calls (or classes not discussed in this book due to space restrictions ), an additional usage example is provided.
Interface Editor "QT designer"
The QT designer allows you to create the application dialog box and main window in what you see is what you get, which is especially useful when creating complex dialogs and la S. In designers, you can drag and drop widgets and set their properties. For example, you can change the text, color, and font of the qlabel.
You can use QT designer to link Multiple widgets in a layout and immediately see the layout effect in the window. If needed, you can even use it to set the signal-slot connection between parts.
The designer's preview mode allows you to check the user interface you created: You can see the response of the layout size change, test the window parts, and observe whether the signal-slot connection has achieved the desired effect.
The designer also has a mode to specify the tab order of the window parts: that is, the access order of the independent parts when the user repeatedly presses the tab key. This is an important aspect of the user interface, so you should always check it. If the tab order is reasonable, a program should be able to operate directly only through the keyboard. Note that if you do not set the tab sequence, QT will automatically set the sequence, which may cause the result not to be what you want.
To use the designer-created dialog box in an application, you need a separate Conversion Tool. The QT designer saves the interface design scheme in XML format as a file with the extension. UI. To use this interface in a program, you must use the command line tool UIC (User Interface compiler) to generate C ++ code from the XML description.
If you use qmake to create a project file, UIC can be used to easily integrate the forms variable created by the designer: Each. UI file to be used is added to the. Pro file. For example, the following line in the. Pro file adds the description of the mydialog. UI dialog box to the project:
Forms + = mydialog. UI
Then qmake creates a rule: UIC uses this rule to generate the C ++ file ui_mydialog.h from the mydialog. UI file. This header file contains the code that implements the Interface Description of the dialog box. (We will discuss in detail the use of the remaining code in this file in the application in Chapter 3 .)
Translation tool "QT language home"
The QT language is used to translate applications from one language to another. As a separate graphical interface tool, QT language providers allow you to easily integrate language translators in software development. Like QT designers, QT translators must also work with external command line tools, including lupdate and lrelease, to update software engineering binary files, replace the words and statements displayed on the user interface that are of medium price in different languages. Lupdate extracts the text to be translated from the source code of the program and generates the translation file according to the definition in the project file:
Translations = application_fr.ts \
Application_nl.ts
Then, we use the GUI program QT interpreter as a graphic interface utility to translate (or edit) language files generated in this way. Finally, lrelease creates an additional binary file that contains the application translation. When the application requests are loaded at startup, the displayed interface is translated. In this way, the lupdate, language, and lrelease can be used together to generate a release version that supports another language without re-writing or compiling the application code.
For all this work, the source code of the application must be converted. In particular, strings representing the text to be translated must be passed to the function qobject: TR () or qapplication: translate (). This completes two things:
It allows QT to dynamically change strings. If you only specify the string "Hello, world!" in the source code! ", It will be used when the application is running. However, if you first send a string through the function tr () of the qobject class or the function translate () of the qapplication class, this function will view the translation file and return a string containing it, replace the original "Hello, world! ".
It allows lupdate to find the function calls to locate the paragraphs to be translated in the source code.
Unfortunately, the simple "Hello, world!" in section 1.1 !" The program cannot be translated into other languages, because we have no! "The string uses tr () or translate (). To fix this problem, we use the following line:
Qlabel label ("Hello, world! ");
Replace:
Qlabel label (qapplication: translate ("mylabel", "Hello, world! "));
The qapplication: translate () function uses the first parameter as the context flag of the text. However, qobject: TR () automatically uses the Class Name of the part we are talking about as the context flag of the text. For example, if you call the tr () method of the qlabel object, QT automatically uses the context name qlabel. This is possible because qlabel inherits from the qobject class as the base class, and therefore inherits the tr () method.
Context relationships are very important because the same text may appear in different places and have different meanings. If the target language uses clear terms for these variants, accurate translation of original text instances will depend on context ). For example, opening an English text may indicate opening a file in a dialog box, but opening a network connection in another dialog box may indicate opening a network connection; the German version of this program should translate the first one to öffnen and the second to aufbauen. When two instances have different context labels, the QT language can distinguish them.
In your program, you should send all the text to the tr () or translate () function. You will find that during code development, the program translation can be completed without much difficulty (if you do not). Once the code is completed, it is boring to carefully check all the text of a large program and manually add tr () or translate. Therefore, the tr () function will be used from the very beginning in the examples of the rest of this book.
(You will see details about internationalization and localization in Chapter 14th)
Create a project
As described in Section 1.1.1, qmake creates a platform-specific makefile from a platform-independent project file. Make or nmake uses the Rules stored in makefile to compile and link the program. However, nmake can only be used with the commercial version of QT and cannot be used with the open-source version of QT. Under GPL license, QT 4 for Windows should replace nmake with GCC and GNU make provided by Linux mingw.
The qmake project file does not require attention to compiler or Linker Options. Therefore, we will use qmake in all examples in this book.
In Windows, if you have a QT commercial license, you can also use qmake to create Microsoft Visual Studio project files. (QT plug-ins are unavailable in the free version of Visual Studio Express. These users need to rely on the command line version of qmake .)
For open-source developers on Windows, code: blocks is a good development environment. It can work with the mingw attached to QT, and even contains the QT 4 Engineering Template. However, to make it work with qmake, you must first prevent it from generating makefile files by itself. To do this, select the project -- Property and mark "this is a custom MAKEFILE file" option. View the project -- Build option and activate the command tab. In the pre-compilation, enter the following command:
Qmake-Project
Qmake
Make. bat
To ensure that qmake is called whenever other programs add new files, check the option "always execute, even if target is up-to-date ". Figure 1.13 shows "Hello, world !" Code: blocks after the program is compiled.
It is useful to save the menu items that start QT designers, QT assistants, or make on the tool menu. In a certain range, you can also use this function to start your own program, which can be specified in configure tools in the secondary menu of the tool menu.
On Mac OS X, the best development environment is xcode IDE. Apple has provided this software for free since OS X 10.3, but it needs to be installed independently. The qmake on the Mac platform has changed accordingly to generate the xcode project file instead of the MAKEFILE file. However, if you don't want to use xcode, just use the command line tool. Simply add-spec macx-G ++ to generate the MAKEFILE file:
Qmake-spec macx-G ++
For comparison,
Qmake-spec macx-xcode
In all QT versions, qmake generates xcode project files for Mac OS X platform. Qmake generates an xcode project from the. Pro file, which will appear in xcode's project management tool later.
Qmake-spec macx-G ++
Generate the MAKEFILE file directly using gcc.
When you develop an application in Linux, the development environment kdevelop may be the best choice. Kdevelop 3.4 provides support for the QT 4 Project. Kdevelop contains a project template and a graphical management tool for qmake project files, which can be seamlessly integrated into IDE.
Except for the first start, kdevelop always displays a blank main window. Select project -- new project will start the project wizard, which will guide you step by step to create a kdevelop project. To use qmake to create a project that supports QT 4, select C ++ -- qmake project -- Basic QT 4 application from the tree menu shown in Figure 1.15. After completing step 1, the wizard also requires the application name and the directory that stores all files.
Next, you can select a source code control tool. If you do not use the source code management system, keep the default option none. The remaining steps allow you to customize the code templates to be inserted into all header files and source files. These usually include the license and the author's name. Figure 1.16 shows the main. cpp file in the main window of the example program after the Wizard is complete.
Press SHIFT + F9 to build and execute the current project. The original output building information is displayed on the messages and application tabs at the bottom, which are automatically opened during the build and execution phases.
The qmake project manager (qmakemanager) is hidden behind the tab of the QT flag on the right. Expand it up, and you can use it to add, remove, or open files graphically. The Project Manager presents different types of source files: kdevelop opens common source files on the new tab and automatically starts the QT designer when a. UI file is encountered.
For those who do not like the bulky IDE, the KDE advanced text editor is a good alternative. It contains a drop-down menu for directly compiling files, as shown in 1.17. Depending on the release version, you may first want to install the Kate-plugins package (in all packages) because it provides Code Completion functions. Through this plug-in, Kate provides an overview of the Chinese methods and member variables in the C and C ++ files, and even allows code fragment management by setting -- configure Kate -- Application -- plug-in.
The Kate Setting Dialog Box provides a level-2 menu, an external tool, in which you can add your own commands, just like in code: blocks, they will appear in the tool-external tool later. Set -- configure the shortcut key to list the keyboard shortcuts.
Metabase compiler MOC (themeta-object compiler)
The signal-Slot Mechanism in QT is not pure C ++, but an extension of the C ++ standard. For this reason, QT provides the command line tool MOC to replace the yellow diamond in the signal-slot structure with the standard C ++. MoC generates additional C ++ code for each class inherited from qobejct. This ensures that the signal-slot connection can be dynamically generated at runtime. It also allows the runtime to dynamically detect the use of qobject as the name of the base class, and even checks whether a class is the base class of another class.
Qt also includes an attribute system. MoC generates required code for this. An attribute is a special feature of a class. It can be set and queried. For example, the qlabel class has a text attribute whose value is a string containing the text displayed by the label. Each attribute has two functions: one for getting the current value, also known as the get method, and the other for changing the current value, also known as the set method ). In the case of qlabel, text () is the get method, which returns the text of the label, and settext () is the set method, which provides a new text for the label.
These two functions are marked as attributes in the class definition, allowing you to query text through qobject: Property () and set text through qobject: setproperty. They all need a string called an attribute as a parameter. The property editor of QT designer determines the attribute value at runtime and allows you to change the attribute. If you use attributes in a separate class, it must inherit the qobject class.
In short, MOC is required whenever a class uses qobject as the base class. Before running the C ++ compiler, each file of any class must use the metachined compiler for preprocessing. In each example, a file prefixed with MOC _ is generated.
For example, if you write your own dialog box class mydialog and use qobject as the base class, the class is defined in mydialog. in the H file, the class is actually implemented in mydialog. in CPP, the metabase compiler must process mydialog. h, then generate moc_mydialog.cpp, and integrate the generated file into the entire project. qmake automatically completes these tasks.
Qt resource compiler RCC
Almost every program uses external resources such as images or images. These resources can be stored in a separate file or embedded into the generated executable file. QT 4 uses the resource compiler RCC to generate a file. The resource compiler obtains information from the Resource Description file ending with the extension. qrc. A. qrc file specifies the path of resources used by the program in the file system, starting from the directory where the. qrc file is located.
If you include a resource file in the qmake project, QT automatically generates a hex encoded array to store the content of the resource file. The QT resource system ensures that the application can use the original directory and file name to access the encoded resources. A. qrc file describes the files required by the Program (using XML. It looks like the following:
<RCC>
<Qresource>
<File> pics/symbols/stop.png </File>
<File> pics/symbols/start.png </File>
<File> pics/symbols/pause.png </File>
</Qresource>
</RCC>
The detailed path is generally understood as relative to the directory where the resource file is located. In this example, we assume that the resource file name is symbols. qrc: Directory: pics/symbols. The directory contains the required images. This directory is under the directory where the source code (including resource files) is located.
In order for qmake to take into account the information from the resource file, the corresponding resources command must be added to the project file:
Resources = symbols. qrc
The image file stop.png in the PICs/symbolsdirectory can be referenced in the program code as follows:
Mylabel-> setpixmap (qpixmap (":/pics/symbols/stop.png "));
To point to a resource, you only need to put a colon in front of the path specified in the. qrc file. (The following diagonal line is not an error. In the logical path tag, the relative path in the file system is specified as an absolute path, and the directory where the source code is located is used as the root directory .) If the resource description file is correctly integrated into the project file, the qpixmap () method can parse the path correctly. This label displays a stop icon.