Qt 5 引入了信号槽的新语法:使用函数指针能够获得编译期的类型检查。使用我们在自定义信号槽中设计的Newspaper
类,我们来看看其基本语法:
//!!! Qt5 #include <QObject> // newspaper.h class Newspaper : public QObject { Q_OBJECT public: Newspaper(const QString & name) : m_name(name) { } void send() const { emit newPaper(m_name); } signals: void newPaper(const QString &name) const; private: QString m_name; }; // reader.h #include <QObject> #include <QDebug> class Reader : public QObject { Q_OBJECT public: Reader() {} void receiveNewspaper(const QString & name) const { qDebug() << "Receives Newspaper: " << name; } }; // main.cpp #include <QCoreApplication> #include "newspaper.h" #include "reader.h" int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); Newspaper newspaper("Newspaper A"); Reader reader; QObject::connect(&newspaper, &Newspaper::newPaper, &reader, &Reader::receiveNewspaper); newspaper.send(); return app.exec(); }
在main()函数中,我们使用connect()函数将newspaper对象的newPaper()信号与reader对象的receiveNewspaper()槽函数联系起来。当newspaper发出这个信号时,reader相应的槽函数就会自动被调用。这里我们使用了取址操作符,取到Newspaper::newPaper()信号的地址,同样类似的取到了Reader::receiveNewspaper()函数地址。编译器能够利用这两个地址,在编译期对这个连接操作进行检查,如果有个任何错误(包括对象没有这个信号,或者信号参数不匹配等),编译时就会发现。
有重载的信号
如果信号有重载,比如我们向Newspaper
类增加一个新的信号:
void newPaper(const QString &name, const QDate &date);
Qt 4 中,我们使用SIGNAL
和SLOT
两个宏来连接信号槽。如果有一个带有两个参数的信号,像上面那种,那么,我们就可以使用下面的代码:
QObject::connect(&newspaper, SIGNAL(newPaper(QString, QDate)),
&reader, SLOT(receiveNewspaper(QString, QDate)));
QT5中可以使用一个函数指针来指明到底是哪一个信号:
void (Newspaper:: *newPaperNameDate)(const QString &, const QDate &) = &Newspaper::newPaper;
QObject::connect(&newspaper, newPaperNameDate,
&reader, &Reader::receiveNewspaper);