结合教程,写出如下关于信号槽的代码,将教程中信号槽两种方式写入同一个界面中。
#include "mainwindow.h" #include <QApplication> #include <QPushButton> #include <QDebug> #include <QHBoxLayout> int main(int argc, char *argv[]) { QApplication a(argc, argv); //MainWindow w; //w.show(); QWidget *myWidget = new QWidget; myWidget->setWindowTitle("Hello World"); //信号槽 QPushButton *button0 = new QPushButton; button0->setText("Quit"); QObject::connect(button0, &QPushButton::clicked, &QApplication::quit);
// Lambda表达式标准输出 QPushButton *button = new QPushButton; button->setText("std::out"); QObject::connect(button, &QPushButton::clicked, [](bool) { qDebug() << "You clicked me!"; }); QHBoxLayout *layout = new QHBoxLayout; //layout->addItem(button0); layout->addWidget(button0); layout->addWidget(button); myWidget->setLayout(layout); myWidget->show(); return a.exec(); }
Qt5中信号槽的定义:
QMetaObject::Connection connect(const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType); QMetaObject::Connection connect(const QObject *, const QMetaMethod &, const QObject *, const QMetaMethod &, Qt::ConnectionType); QMetaObject::Connection connect(const QObject *, const char *, const char *, Qt::ConnectionType) const; QMetaObject::Connection connect(const QObject *, PointerToMemberFunction, const QObject *, PointerToMemberFunction, Qt::ConnectionType) QMetaObject::Connection connect(const QObject *, PointerToMemberFunction, Functor);
connect()一般会使用前面四个参数,第一个是发出信号的对象,第二个是发送对象发出的信号,第三个是接收信号的对象,第四个是接收对象在接收到信号之后所需要调用的函数。也就是说,当 sender 发出了 signal 信号之后,会自动调用 receiver 的 slot 函数。
connect(sender, signal, receiver, slot);
自定义信号槽:
//newspaper.h #ifndef NEWSPAPER_H #define NEWSPAPER_H #include <QObject> //使用信号槽必须继承QBject类 class Newspaper : public QObject { //QBject类及其子类,都必须在第一行写Q_OBJECT //该宏应放于头文件中 Q_OBJECT public: Newspaper(const QString & name) : m_name(name) { } void send() { //emit 的含义是发出newPaper()的信号 emit newPaper(m_name); } //信号函数,返回值为void,参数是类要让外界获取的数据 signals: void newPaper(const QString &name); private: QString m_name; }; #endif // NEWSPAPER_H
//reader.h #ifndef READER_H #define READER_H #include <QObject> #include <QDebug> class Reader : public QObject { Q_OBJECT public: Reader() {} //槽函数 void receiveNewspaper(const QString & name) { qDebug() << "Receives Newspaper: " << name; } }; #endif // READER_H
#include "mainwindow.h" #include "newspaper.h" #include "reader.h" #include <QApplication> #include <QPushButton> #include <QDebug> #include <QHBoxLayout> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); //MainWindow w; //w.show(); Newspaper newspaper("Newspaper A"); Reader reader; //信号连接机制 QObject::connect(&newspaper, &Newspaper::newPaper, &reader, &Reader::receiveNewspaper); newspaper.send(); return app.exec(); }
编译文件,报错——LNK2001,无法链接解析的外部符号。
解决方法:将Project的同级编辑文件删除,重新编译既可。
输出: