qt 信号,槽及反射机制的实现原理 (记录 gui programing with qt 4)

来源:互联网 发布:淘宝查号截图怎么弄 编辑:程序博客网 时间:2024/05/24 06:15

1.首先看一下信号和槽在使用上的几种方式

     One signal can be connected to many slots

     Many signals can be connected to the same slot

     A signal can be connected to another signal

     Connections can be removed

2.利用moc 的预处理去实现信号,槽,反射机制 , moc会生成获得元数据函数,Q_OBJECT,和所有signals的实现。moc处理后的代码可以用任何C++编译器进行编译

    

Qt's Meta-Object System

One of Qt's major achievements has been the extension of C++ with a mechanism for creating independent software components that can be bound together without any component knowing anything about the other components it is connected to.

The mechanism is called the meta-object system, and it provides two key services: signalsslots and introspection. The introspection functionality is necessary for implementing signals and slots, and allows application programmers to obtain "meta-information" about QObject subclasses at run-time, including the list of signals and slots supported by the object and its class name. The mechanism also supports properties (for Qt Designer) and text translation (for internationalization), and it lays the foundation for Qt Script for Applications (QSA).

Standard C++ doesn't provide support for the dynamic meta-information needed by Qt's meta-object system. Qt solves this problem by providing a separate tool, moc, that parses Q_OBJECT class definitions and makes the information available through C++ functions. Since moc implements all its functionality using pure C++, Qt's meta-object system works with any C++ compiler.

The mechanism works as follows:

  • The Q_OBJECT macro declares some introspection functions that must be implemented in every QObject subclass: metaObject(), TR(), qt_metacall(), and a few more.

  • Qt's moc tool generates implementations for the functions declared by Q_OBJECT and for all the signals.

  • QObject member functions such as connect() and disconnect() use the introspection functions to do their work.

All of this is handled automatically by qmake, moc, and QObject, so you rarely need to think about it. But if you are curious, you can check out the QMetaObject class documentation and have a look at the C++ source files generated by moc to see how the implementation works.

原创粉丝点击