[QT Programming Series-17]: Basic framework - why do you need to add Q_OBJECT macro definition when deriving objects?

This code defines a MainWindowclass called , which is QMainWindowa subclass of .

QMainWindowIt is a main window class provided in Qt, which is used to create the main interface of the application. Inherited from Allows QMainWindowfor easy creation of main window applications with standard menu bar, toolbar, status bar and other interface elements.

Q_OBJECTIs a macro that needs to be added when defining a derived QObjectclass. It tells the Qt meta-object compiler (MOC, Meta-Object Compiler) to process the class and generate meta-object code related to signals and slots.

In the header file, MainWindowthe class definition should look like this:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    // 构造函数、成员函数等

public slots:
    // 槽函数声明

private:
    // 私有成员变量、私有函数等

};

#endif // MAINWINDOW_H

In the above code, publicconstructors, member functions, etc. can be declared under the access qualifier. Private member variables, private functions, etc. can be placed privateunder the access qualifier.

By MainWindowadding Q_OBJECTmacros to the class definition and using keywords correctly in the class declaration public slots, slot functions can be defined to respond to signals and perform specific operations.

It should be noted that in the class using the Q_OBJECTmacro , the class must be processed by the Qt meta-object compiler tool MOC, so after the Q_OBJECTmacro is used, the MOC needs to be executed to preprocess the class to generate the meta-object code.

In the Qt build system, QMake or CMake is usually used to automatically handle MOC preprocessing without manual operation.

In addition, when new signals and slots are introduced or Q_OBJECTclasses using macros are modified, MOC preprocessing needs to be re-run to update the meta-object code to ensure that signal and slot connections and calls work properly.

QMainWindowThe class inherited from MainWindowcan be used to create the main window of the application, and define interface elements such as menus, toolbars, status bars, and related slot functions in it to achieve complete application functions.

Remark:

When an object needs to receive signals and handle slot functions, this line of definition must be added.

Guess you like

Origin blog.csdn.net/HiWangWenBing/article/details/131741949