例1:
QSignMapper *mapper = new QSignMapper(this)
QPushButton *btn1 = new QPushButton(this);
btn1->setText("btn1");
QPushButton *btn2 = new QPushButton(this);
btn2->setText("btn2");
mapper->setMapping(btn1,btn1->text());
mapper->setMapping(btn2,btn2->text());
connect(btn1,SIGNAL(clicked()),mapper,SLOT(map()));
connect(btn2,SIGNAL(clicked()),mapper,SLOT(map()));
connect(mapper,SIGNAL(map(QString),this,SLOT(disStr(QString)));
整体的作用是通过一个无参的信号转化成有参的信号,然后传给槽函数进行操作
引自:http://blog.csdn.net/hsl17/article/details/6768322
例2:
今天想自己用Qt编一个Ubuntu下简易的计算器,设想每次按下一个数字键或者运算符,输出界面上都会显示各自数字或字符。
当多个signal连接到一个同一个slot,而且slot对每个signal处理不同时,用到QSignalMapper:
The QSignalMapper class is provided for situations where many signals are connected to the same slot and the slot needs to handle each signal differently.
代码结构如下:
//声明用于显示所按下数字的lineEdit以及各个按钮
QLineEdit* lineEdit = new QLineEdit("0");
lineEdit->setAlignment(Qt::AlignRight);
QPushButton* pushButton = new QPushButton[20];
pushButton[12].setText("1");
pushButton[13].setText("2");
pushButton[14].setText("3");
pushButton[15].setText("-");
......
QSignalMapper* signalMapper = new QSignalMapper;
......
signalMapper->setMapping(&pushButton[12], QString("1"));
signalMapper->setMapping(&pushButton[13], QString("2"));
signalMapper->setMapping(&pushButton[14], QString("3"));
signalMapper->setMapping(&pushButton[15], QString("-"));
......
connect(&pushButton[12], SIGNAL(clicked()),signalMapper, SLOT (map()));
connect(&pushButton[13], SIGNAL(clicked()),signalMapper, SLOT (map()));
connect(&pushButton[14], SIGNAL(clicked()),signalMapper, SLOT (map()));
connect(&pushButton[15], SIGNAL(clicked()),signalMapper, SLOT (map()));
......
connect(signalMapper, SIGNAL(mapped(const QString &)),this, SLOT(setNum(const QString &)));
引自:http://blog.sina.com.cn/s/blog_5e42f31a0100ykaz.html