<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } -->
Qobject 类提供了QT 的核心交互机制,即信号和槽。
关于信号和槽主要有5 个函数
1 connect() 连接信号和槽
2 disconnect() 断开连接
3 connectNotify() 连接时调用此函数
4 disconnectNotify() 断开时调用此函数
5 blockSignal() 是否阻止发送信号
具体的函数格式,可以参看qt的官方说明文档。
下面以例子说明
例子包含三个文件main.cpp GwObject.h GwObject.cpp//main.cpp #include <QtCore/QCoreApplication> #include "GwObject.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); GwObject *g; g = new GwObject; g->startTest(1); //发送一个测试信号 g->blockSignals(true); g->startTest(2); g->blockSignals(false); g->startTest(3); g->disconnect(); g->startTest(4); g->deleteLater(); QObject::connect(g,SIGNAL(destroyed()),&a,SLOT(quit())); return a.exec(); } //GwObject.h #ifndef GWOBJECT_H #define GWOBJECT_H #include <QObject> class GwObject : public QObject { Q_OBJECT public: explicit GwObject(QObject *parent = 0); void startTest(int x); void connectNotify(const char *signal); void disconnectNotify(const char *signal); signals: void test(int); public slots: void onTest(int); }; #endif // GWOBJECT_H //GwObject.cpp #include "GwObject.h" #include <QDebug> GwObject::GwObject(QObject *parent) : QObject(parent) { connect(this,SIGNAL(test(int)),this,SLOT(onTest(int))); } void GwObject::startTest(int x) { emit test(x); } void GwObject::onTest(int x) { qDebug() << "just have a test. id : " << x << endl; } void GwObject::connectNotify(const char *signal) { qDebug() << "connect signal : " << signal << endl; } void GwObject::disconnectNotify(const char *signal) { qDebug() << "disconnect signal : " << signal << endl; }
<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } -->
GwObject.h
1 定义了test (int )信号,test 信号携带了一个int 的信息
2 定义了onTest(int) 槽,接受一个int 的信息
3 构造函数中将test 与onTest 连接了起来。
4 startTest(int x) 将会发送一个test(x) 的信号
5 重载了connectNotify 即当有连接动作时,自动调用此函数
6 重载了disconnectNotify 即当有断开连接动作时,自动调用此函数。
<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } -->
GwObject.cpp 是对GwObject.h 的实现
main.cpp
新建一个GwObject 对象g
首先发送一个test(1) 信号,应该能收到。
然后block 掉。
发送test(2) 信号,应该发不出。
然后取消block
发送test(3) 信号,应该能收到。
然后断开连接.
发送test(4) 信号,应该收不到。
最后将g 删掉
g 被删除时会发送destroy() 信号
连接g 的destroy 与a 的quit, 这样,g 被删除的同时,程序也退出。
具体一些的东西可以看看官方帮助文档。