4.自定义信号槽
具体实现一个自定义newspaper,reader的信号槽
//!!! Qt5
#include <QObject>
////////// newspaper.h
class Newspaper : public QObject
{
Q_OBJECT
public:
Newspaper(const QString & name) :
m_name(name)
{
}
void send()
{
emit newPaper(m_name);
}
signals:
void newPaper(const QString &name);
private:
QString m_name;
};
////////// reader.h
#include <QObject>
#include <QDebug>
class Reader : public QObject
{
Q_OBJECT
public:
Reader() {}
void receiveNewspaper(const QString & name)
{
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();
}
1
//!!! Qt5
2
3
4
////////// newspaper.h
5
class Newspaper : public QObject
6
{
7
Q_OBJECT
8
public:
9
Newspaper(const QString & name) :
10
m_name(name)
11
{
12
}
13
14
void send()
15
{
16
emit newPaper(m_name);
17
}
18
19
signals:
20
void newPaper(const QString &name);
21
22
private:
23
QString m_name;
24
};
25
26
////////// reader.h
27
28
29
30
class Reader : public QObject
31
{
32
Q_OBJECT
33
public:
34
Reader() {}
35
36
void receiveNewspaper(const QString & name)
37
{
38
qDebug() << "Receives Newspaper: " << name;
39
}
40
};
41
42
////////// main.cpp
43
44
45
46
47
48
int main(int argc, char *argv[])
49
{
50
QCoreApplication app(argc, argv);
51
52
Newspaper newspaper("Newspaper A");
53
Reader reader;
54
QObject::connect(&newspaper, &Newspaper::newPaper,
55
&reader, &Reader::receiveNewspaper);
56
newspaper.send();
57
58
return app.exec();
59
}
自定义信号槽需要注意的事项:
- 发送者和接收者都需要是
QObject
的子类(当然,槽函数是全局函数、Lambda 表达式等无需接收者的时候除外); - 使用 signals 标记信号函数,信号是一个函数声明,返回 void,不需要实现函数代码;
- 槽函数是普通的成员函数,作为成员函数,会受到 public、private、protected 的影响;
- 使用 emit 在恰当的位置发送信号;
- 使用
QObject::connect()
函数连接信号和槽。
附件列表