Mapping signal via signalMapper
Article Metadata
Tested with
Devices(s): Emulator
Compatibility
Platform(s): S60 3rd Edition FP1, S60 3rd Edition FP2, S60 5th Edition
Article
Keywords: QSignalMapper
Created: mind_freak
(21 Apr 2009)
Last edited: hamishwillee
(11 Oct 2012)
Contents |
Introduction
This example demonstrates how to use the QSignalMapper, a class for mapping parameterless signals from a set of objects to a single signal that contains a parameter identifying the original sending object.
Preconditions
- Download and install the Qt SDK
Source Code
Main.cpp
#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
#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
#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
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.


(no comments yet)