该类收集一组无参数信号,并使用与发送信号的对象对应的整数、字符串或小部件参数重新发射它们。注意,在大多数情况下,您可以使用lambda将自定义参数传递给插槽。这是较低的成本,并将简化代码。

类支持特定字符串、整数、对象和小部件与特定对象的映射。
QSignalMapper我们可以理解为转发器,此话怎讲呢?比如,按钮点击的响应槽,绑定到QSignalMapper上,QSignalMapper收到按钮的点击后,又通知到另外的控件上做处理。

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QSignalMapper>
#include <QLineEdit>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QSignalMapper *pMapper = new QSignalMapper(this);

QString str = "Button1 Button2 Button3 Button4 Button5";
QStringList strList = str.split(" ");

QVBoxLayout *pLayout = new QVBoxLayout(this);
int nRowCnt = 0;
foreach(const auto& it, strList){
QPushButton *pBtn = new QPushButton(this);
pBtn->setText(it);

connect(pBtn, SIGNAL(clicked()), pMapper, SLOT(map()));
pMapper->setMapping(pBtn, pBtn->text()+"test");
pLayout->addWidget(pBtn);
pBtn->move(10,nRowCnt++*30);
}

QLineEdit *pEdit = new QLineEdit(this);
pEdit->move(10,nRowCnt++*30);
connect(pMapper, SIGNAL(mapped(QString)), pEdit, SLOT(setText(QString)));
pLayout->addWidget(pEdit);
pLayout->addStretch();
setLayout(pLayout);
}

MainWindow::~MainWindow()
{
delete ui;
}

QSignalMapper使用入门_字符串


另外可以用:

(pushButton动态生成的话,可以放容器里,如QList<QPushButton*> lst;)

connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(clicked()));
connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(clicked()));
connect(ui->pushButton_3, SIGNAL(clicked()), this, SLOT(clicked()));
ui->pushButton->setWhatsThis("b1");
ui->pushButton_2->setWhatsThis("b2");
ui->pushButton_3->setWhatsThis("b3");
ui->pushButton->setProperty("ttt","IamSoPoor");
ui->pushButton_2->setProperty("ttt","11");
ui->pushButton_3->setProperty("ttt","22");

void MainWindow::clicked()
{
auto obj = qobject_cast<QPushButton *>(sender());
qDebug()<<obj->text();
qDebug()<<obj->whatsThis();
qDebug()<<obj->property("ttt").toString();
}
void MainWindow::checkboxClicked(bool checked)
{
connect(ui->checkBox1, SIGNAL(clicked(bool)), this, SLOT(checkboxClicked(bool)));
connect(ui->checkBox2, SIGNAL(clicked(bool)), this, SLOT(checkboxClicked(bool)));
connect(ui->checkBox3, SIGNAL(clicked(bool)), this, SLOT(checkboxClicked(bool)));
connect(ui->checkBox4, SIGNAL(clicked(bool)), this, SLOT(checkboxClicked(bool)));
connect(ui->checkBox5, SIGNAL(clicked(bool)), this, SLOT(checkboxClicked(bool)));
connect(ui->checkBox6, SIGNAL(clicked(bool)), this, SLOT(checkboxClicked(bool)));
grp = new QButtonGroup(this);
grp->addButton(ui->checkBox1,0);
grp->addButton(ui->checkBox2,1);
grp->addButton(ui->checkBox3,2);
grp->addButton(ui->checkBox4,3);
grp->addButton(ui->checkBox5,4);
grp->addButton(ui->checkBox6,5);
auto checkBox = qobject_cast<QCheckBox*>(sender());
int id = grp->checkedId();
qDebug()<<"tt"<<checked<<checkBox->objectName()<<id;//checkBox1,whatisthis,property()
QString str = grp->checkedButton()->text();
}

链接:https://pan.baidu.com/s/11BdAJX3dZqIghdWIsX0l5Q
提取码:l3a8