Mapping signal via signalMapper
Jump to navigation
Jump to search
Introduction[edit | edit source]
Preconditions[edit | edit source]
- Download and install the Qt SDK
Source Code[edit | edit source]
Main.cpp[edit | edit source]
- include <QtGui/QApplication>
- include "buttonwidget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStringList fonts;
fonts << "Nokia" << "QT for S60" << "Python" << "J2ME";
ButtonWidget w(fonts);
w.show();
return a.exec();
}
ButtonWidget.h[edit | edit source]
- ifndef BUTTONWIDGET_H
- define BUTTONWIDGET_H
- include <QtGui/QWidget>
- include<QSignalMapper>
- include<QPushButton>
- include<QGridLayout>
- include<QStringList>
class ButtonWidget : public QWidget
{
Q_OBJECT
public:
ButtonWidget(QStringList texts,QWidget *parent = 0);
signals:
void clicked(const QString &text);
private:
QSignalMapper *signalMapper;
};
- endif // BUTTONWIDGET_H
ButtonWidget.cpp[edit | edit source]
- include "buttonwidget.h"
ButtonWidget::ButtonWidget(QStringList texts,QWidget *parent)
: QWidget(parent)
{
signalMapper = new QSignalMapper();
QGridLayout *gridLayout = new QGridLayout;
for (int i = 0; i < texts.size(); ++i) {
QPushButton *button = new QPushButton(texts[i]);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(button, texts[i]);
gridLayout->addWidget(button, i / 3, i % 3);
}
connect(signalMapper, SIGNAL(mapped(const QString &)),
this, SIGNAL(clicked(const QString &)));
setLayout(gridLayout);
}
ButtonWidget::~ButtonWidget()
{
if(signalMapper)
delete signalMapper;
}
Explanation[edit | edit source]
A list of texts is passed to the constructor. A signal mapper is constructed and for each text in the list a QPushButton is created. We connect each button's clicked() signal to the signal mapper's map() slot, and create a mapping in the signal mapper from each button to the button's text. Finally we connect the signal mapper's mapped() signal to the custom widget's clicked() signal. When the user clicks a button, the custom widget will emit a single clicked() signal whose argument is the text of the button the user clicked.