×
Namespaces

Variants
Actions

Using QSignalMapper

From Nokia Developer Wiki
Jump to: navigation, search


Article Metadata
Tested with
Devices(s): Tested on: Nokia 5800 XpressMusic
Compatibility
Platform(s): Qt
Symbian
S60 5th Edition
Article
Keywords: QSignalMapper
Created: User:Kbwiki (01 Apr 2010)
Last edited: hamishwillee (11 Oct 2012)

Description

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. This class collects a set of parameterless signals, and re-emits them with integer, string or widget parameters corresponding to the object that sent the signal. In order to achieve this, QSignalMapper::setMapping() is used to map all the widget's signals to a single QSignalMapper object. Mappings can be removed later using QSignalMapper::removeMappings(). The widget's signals can then be connected to the QSignalMapper::map() slot. Finally, the QSignalMapper::mapped() signal is connected to any custom widget's signal/slot which can do the required processing.

Solution

SignalMapper.h

 class SignalMapper : public QMainWindow
{
Q_OBJECT
public:
SignalMapper(QWidget *parent = 0);
~SignalMapper();
public slots:
void digitClicked(int);
private:
Ui::SignalMapperClass ui;
// 3 Push buttons will provide 3 Signal's when clicked
QPushButton *buttons[3];
// Label is used to display from which Push Button Signal Came
QLabel* mainlabel;
};

SignalMapper.cpp

 SignalMapper::SignalMapper(QWidget *parent)
: QMainWindow(parent)
{
QWidget* mainwindow = new QWidget(this);
QVBoxLayout* mainlayout = new QVBoxLayout(mainwindow);
//create the label & Signal Mapper
mainlabel = new QLabel(mainwindow);
QSignalMapper *signalMapper = new QSignalMapper(this);
//connect the signal mapper's mapped signal to custom widgets slot
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(digitClicked(int)));
 
for (int indx = 0; indx < 3; ++indx)
{
QString text = QString::number(indx);
 
//create the push buttons and enable the mapping
buttons[indx] = new QPushButton(text, mainwindow);
signalMapper->setMapping(buttons[indx], indx);
 
//connect the push buttons signal to signal mappers slot
connect(buttons[indx], SIGNAL(clicked()), signalMapper, SLOT(map()));
mainlayout->addWidget(buttons[i]);
}
mainlayout->addWidget(mainlabel);
mainwindow->setLayout(mainlayout);
setCentralWidget(mainwindow);
}

This page was last modified on 11 October 2012, at 04:16.
75 page views in the last 30 days.