当有多个信号函数(Signal)绑定同一个槽函数(Slot)时,你会有这样的需求,在槽函数中我希望知道到底是哪个信号函数发送出来的信号,这样根据不同的发送者来执行不同的操作。想实现这个功能可以在槽函数中调用 sender() 方法获取发送信号的对象类型。然后进行处理,具体代码如下:

【代码实现】

Notice:代码只贴出了关键部分,只为了演示功能而已。

1
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
#include "cwidget.h"

CWidget::CWidget(QWidget *parent) : QWidget(parent)
{
_button1 = new QPushButton("button1", this);
_button2 = new QPushButton("button2", this);

_button1->setFixedSize(100, 30);
_button2->setFixedSize(100, 30);

_button2->setGeometry(QRect(105, 0, 100, 30));

// 两个按钮同时绑定一个槽函数
connect(_button1, SIGNAL(clicked(bool)), this, SLOT(slotRecv()));
connect(_button2, SIGNAL(clicked(bool)), this, SLOT(slotRecv()));
}

void CWidget::slotRecv()
{
// 获取发送信号的对象存放到 QObject 基类对象中
QObject* obj = sender();
// 把基类对象强制转换成子类对象
QPushButton* button = dynamic_cast<QPushButton*>(obj);
// 获取子类对象文本可以判断出是点了哪个按钮
qDebug() << button->text();
}