The path to Qt learning 2: The Path to qt Learning

Source: Internet
Author: User
Tags gtk wxwidgets

The path to Qt learning 2: The Path to qt Learning
I. Reasons for the article

Teacher bean has a very good Qt tutorial, but only the online version. So I used this to take notes and don't read any text ~~

Ii. Reading Notes 1. Qt learning 2 (2): Qt Introduction 1.1 one-stop solution for Qt

Qt is a well-known C ++ application framework. But it is not just a GUI library, because Qt is very large, not just a GUI component. To some extent, you get a "one-stop" solution by using Qt: you no longer need to study STL or C ++, you no longer need to go around to find third-party libraries that Parse XML, connect to databases, and access the network, because Qt has built these technologies.

1.2 three implementation policies for cross-platform GUI:

API ing:

API ing means that the interface library uses the same API to map it to different underlying platforms. Generally, it is equivalent to extracting the APIs of different platforms from the public. For example, you can name the Button control on Windows and the Button component on Mac OS. When you use a Button, if it is on Windows, it is compiled into a Button control; if it is on Mac OS, It is compiled into a Button component. The advantage of doing so is that all components are self-contained on the original platform and have the same appearance as those on the native platform. The disadvantage is that a lot of work is required to adapt to different platforms when writing library code, only APIs of the same part can be extracted. For example, if the text box of Mac OS contains a spelling check, but it does not exist in Windows, this function cannot be provided. A typical example of this policy is wxWidgets. This is also a standard C ++ library, as large as Qt. Its Syntax looks similar to that of MFC, with a large number of macros. It is said that an MFC programmer can easily convert to wxWidgets.

API simulation:

As mentioned above, API ing will "missing" Specific features of different platforms, while API simulation solves this problem. Different APIs on different platforms are simulated using the code of the tool library. According to the preceding example, the text box on Mac OS has a spelling check, but Windows does not. Then, the tool Library provides a spelling detection algorithm, so that the text box in Windows has the same function. A typical example of API simulation is wine, a Windows simulator on Linux. It simulates most Win32 APIs on Linux so that Linux can run Windows programs through wine. It can be seen that the biggest advantage of API simulation is that the application can run on a specific platform without re-compiling. Another example is DirectX provided by Microsoft. This development library will block the specific functions provided by different graphics card hardware. When using this library, you don't have to worry about the differences between hardware. If some graphics cards do not provide this function, the SDK will implement it using software. (For examples, refer to the wonderful discussion at the end of this Article .)

GUI simulation:

Any platform provides graphic rendering functions, such as painting points, draw lines, and images. Some tool libraries use these basic functions to draw their own components in different ways, which is GUI simulation. The workload of GUI simulation is undoubtedly very large, because you need to use the most basic drawing functions to draw all the components, and it is hard to prove that this painting is exactly the same as that of the native component. However, the advantage of this generation of price is that you can easily modify the component's appearance-just modify the component's rendering function. Many cross-platform GUI Libraries use this policy, such as gtk + (a graphical interface library in C language. The use of C language elegantly implements object-oriented programming. However, this also brings about a problem-using a large number of type conversion macros to simulate polymorphism, and its function names are generally long, using underscores to separate words, it looks like the same as Linux. Gtk + is not a simulated Native Interface, but has its own style, so sometimes it is incompatible with the interface of the operating system .), Swing and our Qt.

2. Qt learning 2 (3): Hello, world! 2.1 Simple Analysis of the main Function
#include <QApplication>#include <QLabel>int main(int argc, char *argv[]){    QApplication app(argc, argv);    QLabel label("Hello, world");    label.show();    return app.exec();}

Explanation:

The first two rows are the include statements of C ++. Here we introduce the QApplication and QLabel classes. The first sentence in the main () function is to create an instance of the QApplication class. For Qt programs, the main () function generally creates an application Object (the GUI program is QApplication, and the non-GUI program is QCoreApplication. QApplication is actually a subclass of QCoreApplication .) Start, followed by the actual business code. This object is used to manage the lifecycle of the Qt program and enable the event loop, which is all necessary. After creating a QApplication object, we can directly create a QLabel object. The constructor assigns a value of "Hello, world". Of course, this line of text can be displayed on the QLabel. Finally, call the show () function of QLabel to display it. At the end of the main () function,Call app.exe c () to enable the event loop.. Now we can simply understand the event loop as an infinite loop. Because of this, we have built a QLabel object on the stack, but it can always be displayed there (imagine if it is not an infinite loop, the main () function will immediately exit, of course, the QLabel object is directly analyzed ).

2.2 another way of writing hello world

Can I rewrite the above program into the following code?

#include <QApplication>#include <QLabel>int main(int argc, char *argv[]){    QApplication app(argc, argv);    QLabel *label = new QLabel("Hello, world");    label->show();    return app.exec();}

The answer is,NoYes We recommend that you do this.!

First, follow the standard C ++ to see this program. Memory leakage exists here. When exec () Exits (that is, when the event loop ends. When the window is closed, the event loop ends.) label cannot be deleted. This causes memory leakage. Of course, since the program ends, the operating system will recycle the memory, so this problem will not be very serious. Even if you modify the code and run it again, there will be no errors.

Early versions of Qt may have problems (For details, refer to the section with strikethrough at the end of this article, but bean has not been tested. I just saw this article), but there is basically no problem in the new version of Qt. In the new version of Qt, the real-time mechanism of app.exec(is fixed. When the last component is closed, the main component cycle (app.exe c () exits and the main () function ends (the app will be destroyed at this time ). This means that all the visual elements have been disabled, and the QPaintDevice has no QApplication instance as mentioned later. In addition, if you explicitly close the QApplication instance, for example, call a function such as qApp-> quit (), the last action of QApplication is to close all windows. Therefore, even in this case, the class issue does not occur. Because in the main () function, when the main () function ends, the operating system recycles the resources occupied by the process, which is equivalent to no memory leakage. However, there is a potential problem: the operating system only roughly releases the occupied memory and does not call the object's destructor (which is different from calling the delete operator ), therefore, it is very likely that some resources will not be "correctly" released. In fact, the latest version of Sailfish OS has the following code:

#include <QApplication>int main(int argc, char *argv[]){    QScopedPointer<QApplication> app(new QApplication(argc, argv));    QScopedPointer<QQuickView> view(new QQuickView);    view->setSource("/path/to/main.qml");    ...    return app->exec();}

This Code not only creates component instances on the stack, but also creates the QApplication itself on the stack. However, note that it usesSmart pointerTherefore, we do not need to consider the resource occupation caused by the direct release of memory by the operating system.

Of course, the permission does not necessarily mean that we recommend using it like this. After all, this is a bad usage (just as we do not recommend using exception control business logic) because of Memory leakage. It is also bad for program maintainers. Therefore, we recommend creating components on the stack. Because the error probability of manual management of new and delete is much higher than that of automatic control on the stack. In addition, there is no difference between creating a stack and creating a stack.

If you must create an object on the stack, add the following statement:

label->setAttribute(Qt::WA_DeleteOnClose);

This prompt is enough to tell the program maintainer that you have considered the memory issue.

Early versions of Qt may have problems:
Seriously, the label is built on the stack, and the app is built on the stack. This means that the label will be analyzed after the app. That is, the life cycle of the label is longer than that of the app. This is a big taboo in Qt programming. In Qt, all qpaintdevices must be created and used with a QApplication instance. If you are curious, you can mention that QLabel inherits from QWidget, and QWidget is a subclass of QPaintDevice. The above code is normal because the label is disabled when the app exits. In this way, all qpaintdevices of the label are not accessible. However, if the component is not closed when the app exits, the program will crash. (If you want to know how to exit the app, but the component does not exit, beans can tell you that when your program opens a webpage drop-down box, close the window, your program will crash !)

3. Qt learning 2 (4): Signal slot 3.1 Signal and slot Overview

The so-called signal slot is actuallyObserver Mode. When an event occurs, for example, when a button detects that it has been clicked, it sends a signal ). Such sending has no purpose, similar to broadcasting. If an object is interested in this signal, it will use the connect function, which means to process the signal with its own function (becoming a slot. That is, when the signal is sent, the connected slot function is automatically called back. This is similar to the observer mode: when an event of interest occurs, an operation is automatically triggered. (Here I would like to mention that the Qt signal slot is implemented with additional processing, which is not the implementation method of the GoF classic observer mode.)

3.2 connect function

In Qt 5, QObject: connect () has five reloads:

QMetaObject::Connection connect(const QObject *, const char *,                                const QObject *, const char *,                                Qt::ConnectionType);QMetaObject::Connection connect(const QObject *, const QMetaMethod &,                                const QObject *, const QMetaMethod &,                                Qt::ConnectionType);QMetaObject::Connection connect(const QObject *, const char *,                                const char *,                                Qt::ConnectionType) const;QMetaObject::Connection connect(const QObject *, PointerToMemberFunction,                                const QObject *, PointerToMemberFunction,                                Qt::ConnectionType)QMetaObject::Connection connect(const QObject *, PointerToMemberFunction,                                Functor);

Analysis:
First, the sender type is const QObject.The signal type is const char, The volume er type is const QObjectThe slot type is const char. This function processes signal and slot as strings. Second, sender and consumer er are also const QObjectBut both signal and slot are const QMetaMethod &. We can think of each function as a subclass of QMetaMethod. Therefore, QMetaMethod can be used for type comparison. Third, sender is also const QObject, Signal and slot are also const charBut it lacks the aggreger. This function uses the this pointer as the handler. Fourth, both sender and consumer er exist, both of which are const QObject.But the signal and slot types are PointerToMemberFunction. You should know the name. This is a pointer to the member function. Fifth, there is no difference between the first two parameters. The last parameter is of the Functor type. This type can be static functions, global functions, and Lambda expressions.

3.3 signal and slot Parameters

The signal slot must be consistent with the slot parameters. The so-called consistency is that the parameter type is consistent. If they are inconsistent, it is allowed that the slot function has fewer parameters than the signal. Even so, the sequence of the parameters in the slot function must be consistent with those in the front of the signal. This is because you can ignore the data sent from the signal in the slot function (that is, the slot function has fewer parameters than the signal), but it cannot be said that the signal does not have the data at all, you need to use it in the slot function (that is, the slot function has more parameters than the signal, which is not allowed ).

Qt5 can use Lambda expressions, which is a special feature compared to Qt4.

4. Qt learning 2 (5): Custom signal slot 4.1 observer Mode

The signal slot is not provided by the GUI module, but one of the core features of Qt. Therefore, we can use the signal slot in common console programs.

The classic observer mode usually reports the example of paper and subscriber when giving an example. There is a Newspaper and a Subscriber. Subscriber can subscribe to Newspaper. In this way, when Newspaper has new content, Subscriber can be notified immediately. In this example, the observer is Subscriber and the observer is Newspaper. In the classic implementation code, the observer registers itself to a container of the observer (for example, subscriber. registerTo (newspaper )). When any change occurs to the observer, the observer will actively traverse the container and notify each observer (newspaper. notifyAllSubscribers () in turn ()).

4.2 understand the observer mode in Qt

Only classes that inherit the QObject class can have the capability of signal slots.

Only classes that inherit the QObject class can have the capability of signal slots. Therefore, in order to use the signal slot, the QObject must be inherited. Any QObject class (whether directly or indirectly) should write Q_OBJECT In the first line of code. This macro should be added whether or not the signal slot is used. The macro expansion will provide the signal slot mechanism, internationalization mechanism, and C ++ RTTI-based reflection capability provided by Qt for our class. Therefore, if you think that your class does not need to use the signal slot, it is wrong not to add this macro.

4.3

Many other operations depend on this macro. Note that this macro will be introduced by moc (we will introduce moc in later sections. Here you can understand it as a pre-processor, which is executed earlier than the C ++ pre-processor .) Special processing is not just as simple as macro expansion. Moc will read the header file marked with Q_OBJECT and generate a file prefixed with moc _. For example, newspaper. h will generate moc_newspaper.cpp. You can view the file in the build directory to see what is added. Note that moc only processes class declarations marked with Q_OBJECT in the header file and does not process similar declarations in the cpp file. Therefore, if our Newspaper and Reader classes are located in main. cpp, moc processing cannot be obtained. The solution is to manually call the moc tool to process main. cpp and change # include "newspaper. h" in main. cpp to # include "moc_newspaper.h. However, this is a very tedious step. To avoid such modification, we should put it in the header file. Many beginners may encounter inexplicable errors. When Q_OBJECT is added, the error occurs. A large part is caused by the failure to notice that the macro should be placed in the header file.

4.4

The signal is a function name, and the return value is void (because the return value of the signal cannot be obtained, no value is returned). The parameter is the data that needs to be known to the outside world. The signal is used as the function name and does not need to be added to the cpp function (we once said that the Qt program can be compiled using common make. How can an unimplemented function name be compiled? The reason is that in moc, moc will help us implement the function body required by the signal function. Therefore, moc does not simply expand Q_OBJECT, but does a lot of additional operations ).

4.5

In Qt 5, any member function, static function, global function, and Lambda expression can be used as a slot function. Unlike the signal function, the slot function must complete its own implementation code. A slot function is a common member function. As a member function, it is also affected by access controllers such as public and private. (We didn't say that the signal would also be affected. In fact, if the signal is private, this signal cannot be connected outside the class, and it makes no sense .)

4.6 precautions for custom signal slots:

(1) Both the sender and receiver must be sub-classes of QObject (unless, of course, the slot function is a global function, Lambda expression, or other receiver-less );
(2) Use signals to mark the signal function. The signal is a function declaration that returns void without implementing function code;
(3) The slot function is a common member function. As a member function, it will be affected by public, private, and protected;
(4) use emit to send signals at the right position;
(5) use the QObject: connect () function to connect signals and slots.

4.7 differences between Qt 4 and Qt 5 [important]

(1) Reader class. The receiveNewspaper () function is placed in the public slots block. In Qt 4, the slot function must be placed in the code block modified by slots and use the access control operator for access control. The principle is the same as that of other functions. The default value is private. If you want external access, it should be public slots. If you only need to access in the subclass, it should be protected slots.

(2) In the main () function, QObject: connect () function, the second and fourth parameters need to be converted into strings using the SIGNAL and SLOT macros (details are described in the previous section ). Note that the macro parameters of SIGNAL and SLOT do not take the function pointer, But remove the function declaration of the returned value, and the const parameter modifier is negligible.

(3) The following describes another point. We mentioned that "a slot function is a common member function. As a member function, it will be affected by public, private, and protected ", public and private modifiers are provided for the compiler to check during the compilation period, so their impact lies in the compilation period. For the Qt4 signal slot connection syntax, the connection is completed at runtime, so even the private slot function can be connected as a slot. However, if you use the new Qt5 syntax, the new syntax provides the compile-time check (getting the function pointer), so the pointer to the private function cannot be compiled.

5. Qt learning 2 (6): Introduction to the Qt Module

Note: because the original text is in good format, it is very difficult to paste it and change the format, and it is not easy to read. Next, paste the original image.

5.1 Qt Basic module

5.2 Qt extension module

The Qt extension module has more options:

5.3 Qt 4 Module

It should be emphasized that the Qt extension module is not a required part of Qt, so Qt may provide more extension modules in future versions, here, we only provide some parts that will be included in Qt 5, and some others, such as Qt Active and Qt QA, may appear in beta and later versions.

Qt 4 is also divided into several modules, but these modules are somewhat different from Qt 5. The following is the Qt 4 module:

6. Qt learning 2 (7): MainWindow introduction 6.1 menu bar, taskbar, toolbar, and title bar

Try to recall the classic main window, which is usually composed ofTitle Bar, OneMenu Bar, SeveralToolbarAnd oneTaskbar. Between these child components is our workspace. In fact, QMainWindow is such a layout. (These concepts are very important for the programmers who want to do the desktop program, I will do the visual programming tool development is also, on these concepts, see: http://www.360doc.com/content/11/1215/17/8263158_172495415.shtml)

Note:The toolbar can be moved.

6.2 MainWindow

If you directly run the project created by Qt,

7. Qt learning 2 (8): Add action 7.1 QAction class

7.2 qrc

8. Qt learning path 2 (9): resource file 8.1: The resource file is compiled into the PE.

9. Path to Qt learning 2 (10): Object Model

This chapter is very important and also an explanation of moc. Classic and not long. I plan to post them all ~~

10. Qt learning path 2 (11): layout manager

I found that taking notes with images is convenient for typographical layout, but another problem is the lack of information. For example, if I want to search for a word, Images cannot be searched, therefore, we should use the HTML editor instead of the Markdown editor at the time. However, in the future, we should have at least enough keyword indexes for important information layout ~~~

10.1 GUI interface and layout Introduction

10.2 layout manager provided by Qt

(1) QHBoxLayout: Layout from left to right in the horizontal direction;

(2) QVBoxLayout: Layout from top to bottom in vertical direction;

(3) QGridLayout: Layout in a grid, similar to a table in HTML;

(4) QFormLayout: according to the table layout, each row is preceded by a piece of text, followed by a component (usually an input box), similar to the HTML form;

(5) QStackedLayout: The stacked layout allows us to stack several components in the Z axis direction to form a one-page wizard effect.

10.3 Qt 4 the same code compilation, note connect

11. Qt learning path 2 (13): Dialog Box introduction 11.1 dialog box

Many functional components that cannot or are not suitable for the main window must be set in the dialog box. A dialog box is usually a top-level window that appears at the top of the program,For short-term tasks or simple user interaction. Although the appearance of the Ribbon interface reduces the chance of using the dialog box to a certain extent, we can still find many dialogs in the latest Office version. Therefore, in the foreseeable future, the dialog box will always exist in our program.

11.2 modal dialog box and non-Modal Dialog Box

The dialog box is divided into modal dialog box and non-modal dialog box. The modal dialog box blocks the input of other windows in the same application. Modal dialogs are common, such as the "open file" function. You can try to open a file in Notepad. When the open file dialog box appears, we cannot operate the window except this dialog box. In contrast, a non-modal dialog box, such as a Search dialog box, allows you to edit the content of notepad while displaying the Search dialog box.

Qt supports modal and non-modal dialogs. Qt has two levels of modal dialogs: ApplicationProgram-level modal and window-level ModalThe default mode is the application-level mode. The application-level Mode means that when a dialog box of this mode appears, the user must first interact with the dialog box until the dialog box is closed before accessing other windows in the program. Window-level Mode means that the mode only blocks the window associated with the dialog box, but still allows the user to interact with other windows in the program. Window-level modal mode is especially suitable for multi-window mode. For more details, see previous articles.

The strength of Qt

Here, I want to plug in something of my own ~~

I implemented the following:

Void MainWindow: open () {// modal // QDialog dialog (this); // specify the parent pointer // dialog. setWindowTitle (tr ("Hello, dialog! "); // Dialog.exe c (); // non-modal, because it cannot be created on the stack. Otherwise, QDialog * dialog = new QDialog (this) is flashed ); dialog-> setWindowTitle (tr ("Hello, dialog! "); Dialog-> show ();}

This solves the problem ~~

In the previous section, we learned from Qt 2 (10): object model.

This is a very important mechanism of Qt and must be remembered ~~

Boldly create on the stack ~~

12. Qt learning path 2 (14): Dialog Box data transmission 12.1 reason

The modal dialog box uses the exec () function to display it. The true meaning of the exec () function is to enable a new event loop (we will introduce the concept of the event in detail in later sections ). The so-called event loop can be understood as an infinite loop. After the event loop is enabled, Qt can monitor various events triggered by the system. This event loop is equivalent to a round robin function. Since it is an infinite loop, of course, the code will be blocked when the event loop is enabled, and subsequent statements will not be executed. Therefore, for the modal dialog box displayed by exec (), we can obtain the data value directly from the dialog box object after the exec () function.

13. Qt learning 2 (18): Events

To ensure quick start, skip several independent sections of the introduction module. Later, take a closer look and jump to the event chapter. However, it is worth reading carefully.

13.1 event-driven

Events are the basic concept of event drive. The emergence of events makes the program code not run in the original linear order. Think about it. From the beginning of the C language, our program is to execute code in a linear order: After this statement is executed, the next statement is executed. After this function is executed, start to execute the next function. Such a program design style similar to "batch processing" is obviously not suitable for processing complex user interactions. Let's imagine the scenario of user interaction: We designed a bunch of functions on the interface, and the user clicked "Open File" to start opening the file; after clicking "save file", the user starts to save the file. We do not know what operations the user wants to perform, so we cannot predict which function will be called next. If we have designed an "save file as" operation, this operation will never be called if you do not click it. This is the so-called "event-driven". The execution sequence of our programs is not linear, but the execution of programs is driven by events. No event, the program will be blocked and no code will be executed.

Compared with other GUI frameworks, Qt gives us an extra option: Signal slot.

13.2 events and signal Slots

But this is not a thing.

13.3 process of Event Processing

Copyright statement: you are welcome to repost it. Just specify the source! If you do not like it, please leave a message to explain the reason and step on again. Thank you. I can also know the reason and keep improving !!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.