发送者和接收者都需要是QObject的子类(当然,槽函数是全局函数、Lambda 表达式等无需接收者的时候除外);
使用 signals 标记信号函数,信号是一个函数声明,返回 void,不需要实现函数代码;
槽函数是普通的成员函数,作为成员函数,会受到 public、private、protected 的影响;
使用 emit 在恰当的位置发送信号; 使用QObject::connect()函数连接信号和槽。
//!!! Qt4
#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>
#
class
Reader
:
public
QObject
{
Q_OBJECT
public
:
Reader
(
)
{
}
public
slots
:
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
,
SIGNAL
(
newPaper
(
QString
)
)
,
&
reader
,
SLOT
(
receiveNewspaper
(
QString
)
)
)
;
newspaper
.
send
(
)
;
return
app
.
exec
(
)
;
}
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
//!!! Qt4
#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
(
)
{
}
public
slots
:
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
,
SIGNAL
(
newPaper
(
QString
)
)
,
&
reader
,
SLOT
(
receiveNewspaper
(
QString
)
)
)
;
newspaper
.
send
(
)
;
return
app
.
exec
(
)<span class="crayon-sy" style="margin: 0px; padding: 0px; border: 0px; font-style: inherit; font-variant: inherit; font-weight: inherit !important; font-stretch: inherit; font-size: inh
|