QSignalMapper的使用
1. 可以吧无参数的信号转换为带int参数、带QString参数、带QObject参数、带QWidget参数的信号,
假如Qwidget上有许多Button,如果一一建立信号槽,显得繁琐,这时我们可以使用QSignalMapper
- #include "MainWindow.h"
- #include "ui_MainWindow.h"
- #include <QHBoxLayout>
- #include <QVBoxLayout>
- #include <QString>
- #include <QStringList>
- #include <QGridLayout>
- #include <QPushButton>
- #include <QLineEdit>
- #include <QSignalMapper>
-
- MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow)
- {
- ui->setupUi(this);
- init();
- }
-
- MainWindow::~MainWindow()
- {
- delete ui;
- }
-
- void MainWindow::init()
- {
- QGridLayout *pLayout = new QGridLayout();
- this->centralWidget()->setLayout(pLayout);
-
- QString str = "Button1,Button2,Button3,Button4,Button5,Button6,Button7,Button8";
- QStringList strList = str.split(",");
- QSignalMapper *pMapper = new QSignalMapper();
-
- for (int i = 0; i < strList.length(); ++i)
- {
- QPushButton *pBtn = new QPushButton;
- pBtn->setText(strList.at(i));
-
- connect(pBtn, SIGNAL(clicked()), pMapper, SLOT(map()));
- pMapper->setMapping(pBtn, pBtn->text());
-
-
- pLayout->addWidget(pBtn, i, 0);
-
- }
- QLineEdit *pEdit = new QLineEdit();
- connect(pMapper, SIGNAL(mapped(QString)), pEdit, SLOT(setText(QString)));
- pLayout->addWidget(pEdit, 0, 1);
-
- }
- 转自:http://blog.csdn.net/mcgrady_tracy/article/details/6996947