[Translation] Introduction to Qt Meta Object System

Qt's meta-object system provides signal and slot mechanisms for communication between objects, runtime type information, and dynamic attribute systems.

The meta-object system is based on three aspects:

  1. The QObject class provides a base class for objects that can take advantage of the meta-object system.
  2. The Q_OBJECT macro is used to enable meta-object features such as dynamic properties, signals, and slots.
  3. The meta-object compiler ( moc ) provides the code needed to implement meta-object features for each QObject subclass.

The moc tool reads C++ source files. If it finds the Q_OBJECT macro declaration in the class , it generates another C++ source file that contains the meta-object code for each class. The generated source files are either included in the source file of the class, or more usually compiled and linked with the implementation of the class.

In addition to providing the signal and slot mechanism for communication between objects, the meta-object code also provides the following functions:

  1. QObject:: metaObject () returns the associated meta object of the class.
  2. QMetaObject:: className () returns the class name string at runtime, without the need to support native runtime type information (RTTI) through the C++ compiler.
  3. QObject:: inherits () returns whether the object inherits QObject or its subclasses.
  4. QObject:: tr () is an internationalized conversion string.
  5. QObject:: setProperty () and QObject:: property () dynamically set and get properties by name.
  6. QMetaObject:: newInstance () Constructs a new instance of the class.

You can also use qobject_cast () on the QObject class to perform dynamic casts. The behavior of the qobject_cast () function is similar to the standard C++ dynamic dynamic_cast (), and its advantage is that it does not require RTTI support. It tries to cast its parameters to the pointer type specified in angle brackets. If the type of the object is correct (determined at runtime), it returns a non-zero pointer; if the type of the object is incompatible, it returns nullptr.

Although you can use QObject as the base class without using the Q_OBJECT macro and meta-object code, if you do not use the Q_OBJECT macro, the signals, slots, and other features will be unavailable. From the perspective of the meta-object system, a QObject subclass without meta-code is equivalent to the nearest ancestor with meta-object code. For example, this means that QMetaObject:: className () will not return the actual name of the class, but the class name of the ancestor.


Therefore, it is strongly recommended that all subclasses of QObject use the Q_OBJECT macro, regardless of whether they actually use signal slots and attributes.

Guess you like

Origin blog.csdn.net/kenfan1647/article/details/114856058