#include "signals.h"
Signals::Signals(QWidget *parent)
: QDialog(parent)
{
resize(200,200);
QSignalMapper *signal_mapper = new QSignalMapper(this);//创建一个QSignalMapper一对象
//控件定义
mainLayout = new QGridLayout(this);
PushButton1 = new QPushButton(tr("QPushButton1"));
PushButton2 = new QPushButton(tr("QPushButton2"));
ToolButton1 = new QToolButton;
ToolButton2 = new QToolButton;
ToolButton1->setText(tr("ToolButton1"));
ToolButton2->setText(tr("ToolButton2"));
//控件布局
mainLayout->addWidget(PushButton1,0,0);
mainLayout->addWidget(PushButton2,1,0);
mainLayout->addWidget(ToolButton1,2,0);
mainLayout->addWidget(ToolButton2,3,0);
setLayout(mainLayout);
//将需要区分的Button连接到QSignalMapper上的map()
connect(PushButton1, SIGNAL(clicked(bool)),signal_mapper, SLOT(map()));
connect(PushButton2, SIGNAL(clicked(bool)),signal_mapper, SLOT(map()));
connect(ToolButton1, SIGNAL(clicked(bool)),signal_mapper, SLOT(map()));
connect(ToolButton2, SIGNAL(clicked(bool)),signal_mapper, SLOT(map()));
//setMapping是个重载函数,为button设置id 或者text 或者widget object
//这里我们使用为button设定id
signal_mapper->setMapping(PushButton1,1);
signal_mapper->setMapping(PushButton2,2);
signal_mapper->setMapping(ToolButton1,3);
signal_mapper->setMapping(ToolButton2,4);
//然后将按钮触发的信号mapped连接到自定义槽然后将id(QString,QObject等类型)传过去进行处理
connect(signal_mapper,SIGNAL(mapped(int)),this,SLOT(caonimaSlot(int)));
}
Signals::~Signals()
{
}
void Signals::caonimaSlot(int num)
{
switch(num)
{
case 1:
qDebug()<< PushButton1->text() <<endl;
break;
case 2:
qDebug()<< PushButton2->text() <<endl;
break;
case 3:
qDebug() << ToolButton1->text() <<endl;
break;
case 4:
qDebug() << ToolButton2->text() <<endl;
break;
default:
break;
}
}