2014年02月28日 星期五 09:57
简单来说,Qt中的Signal & Slots机制提供了一种事件驱动的编程机制,可以让不同的对象相互关联起来,对象A的事件可以触发对象B的某个动作,而对象A和对象B既可以在同一个线程中,也可以在不同的线程,这种机制是类型安全和线程安全的,从而大大简化的编程的复杂度和错误发生的几率。
Qt的官方文档中有如下介绍:
Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from the features provided by other frameworks.
All classes that inherit from QObject or one of its subclasses (e.g., QWidget) can contain signals and slots. Signals are emitted by objects when they change their state in a way that may be interesting to other objects. This is all the object does to communicate. It does not know or care whether anything is receiving the signals it emits. This is true information encapsulation, and ensures that the object can be used as a software component.
Slots can be used for receiving signals, but they are also normal member functions. Just as an object does not know if anything receives its signals, a slot does not know if it has any signals connected to it. This ensures that truly independent components can be created with Qt.
You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal. (This will emit the second signal immediately whenever the first is emitted.)
Together, signals and slots make up a powerful component programming mechanism.
我们的Qt Tutorial 012中已经使用了此机制,下面是一个更简单的编程示例:
sldemo.h部分代码:
#ifndef SLDEMO_H #define SLDEMO_H #include <QObject> class SLDemo : public QObject { Q_OBJECT public: explicit SLDemo(QObject *parent = 0); void setValue(int value); signals: void valueChanged(int newValue); public slots: void printValue(int value); private: int i; }; #endif // SLDEMO_H
sldemo.cpp部分代码:
#include "sldemo.h" #include <QDebug> SLDemo::SLDemo(QObject *parent) : QObject(parent) { } void SLDemo::setValue(int value){ i=value; emit valueChanged(value); } void SLDemo::printValue(int value){ qDebug() << value; }
主程序main.cpp部分代码:
#include <QCoreApplication> #include <QDebug> #include <QObject> #include "sldemo.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); SLDemo d; QObject::connect(&d,SIGNAL(valueChanged(int)),&d,SLOT(printValue(int))); for(int i=0;i<100;i++){ d.setValue(i); } return a.exec(); }
参考资料:
https://qt-project.org/doc/qt-5.0/qtcore/signalsandslots.html
Zeuux © 2024
京ICP备05028076号