QSignalMapper使用案例
时间: 2023-07-11 10:16:17 浏览: 65
下面是一个简单的QSignalMapper使用案例:
```cpp
#include <QtWidgets>
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = nullptr)
: QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout(this);
QPushButton *button1 = new QPushButton("Button 1", this);
QPushButton *button2 = new QPushButton("Button 2", this);
QPushButton *button3 = new QPushButton("Button 3", this);
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
QSignalMapper *mapper = new QSignalMapper(this);
connect(button1, SIGNAL(clicked()), mapper, SLOT(map()));
connect(button2, SIGNAL(clicked()), mapper, SLOT(map()));
connect(button3, SIGNAL(clicked()), mapper, SLOT(map()));
mapper->setMapping(button1, "Button 1 clicked");
mapper->setMapping(button2, "Button 2 clicked");
mapper->setMapping(button3, "Button 3 clicked");
connect(mapper, SIGNAL(mapped(QString)), this, SLOT(handleButtonClicked(QString)));
}
private slots:
void handleButtonClicked(QString text)
{
QMessageBox::information(this, "Button clicked", text);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyWidget widget;
widget.show();
return app.exec();
}
```
在上面的代码中,我们创建了三个QPushButton,并将它们添加到一个垂直布局中。然后,我们创建了一个QSignalMapper,并将每个QPushButton的clicked()信号连接到QSignalMapper的map()槽函数上。接着,我们使用QSignalMapper的setMapping()函数将每个QPushButton和一个字符串映射在一起,这个字符串是在按钮被点击时将会传递给槽函数的参数。最后,我们将QSignalMapper的mapped()信号连接到MyWidget的handleButtonClicked()槽函数上,这个槽函数会弹出一个消息框,显示按钮被点击的文本。这样,当任意一个QPushButton被点击时,handleButtonClicked()槽函数就会被调用,并且会显示对应的文本。