Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the source signal's parameters while using QSignalMapper?

I ran into a problem that I need to keep the mapped source signal's parameters. So far I only found examples to map signals without any parameter. For example, the clicked() signal:

signalMapper = new QSignalMapper(this);
signalMapper->setMapping(taxFileButton, QString("taxfile.txt"));

connect(taxFileButton, SIGNAL(clicked()),
     signalMapper, SLOT (map()));

connect(signalMapper, SIGNAL(mapped(QString)),
     this, SLOT(readFile(QString)));

However, I would need to map some signal with its own parameters, for example the clicked(bool) signal, then the SLOT need to have two arguments doStuff(bool,QString):

connect(taxFileButton, SIGNAL(clicked(bool)),
     signalMapper, SLOT (map()));

connect(signalMapper, SIGNAL(mapped(QString)),
     this, SLOT(doStuff(bool,QString)));

However, it does not work like this? Is there any work around?

Thanks!

like image 209
Wang Avatar asked Dec 21 '12 11:12

Wang


1 Answers

QSignalMapper does not provide functionality to pass signal parameters.

see documentation:
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.

There are the ways to solve that:

If Qt4 is used then I'd suggest to implement your own signal mapper which supports parameters what you need.
QSignalMapper implementation would be good example to start.

But if Qt5 is used then you can do exactly what you need without usage QSignalMapper at all. Just connect signal to lambda:

connect(taxFileButton, &TaxFileButton::clicked, [this](bool arg) {
    doStuff(arg, "taxfile.txt");
}  );

I assume taxFileButton is instance of TaxFileButton class.

If C++11 lambda is not suitable for some reason then tr1::bind could be used to bind this and "taxfile.txt" values.
Please note such connection will not be disconnected automatically when this object is destroyed. More details are here.

like image 170
Alexander Stepaniuk Avatar answered Nov 10 '22 18:11

Alexander Stepaniuk