7

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!

Wang
  • 7,250
  • 4
  • 35
  • 66

1 Answers1

7

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.

Alexander Stepaniuk
  • 6,217
  • 4
  • 31
  • 48
  • So there is NO easy way to do this in Qt4 other than implementing my own mapper class? – Wang Dec 24 '12 at 16:12
  • 2
    I'd be happy to get easy way as well :) . For now similar task in my project is solved in the way I described for Qt4. – Alexander Stepaniuk Dec 24 '12 at 18:15
  • Very nice. I needed it for the QLineEdit::textEdited event to map various controls into an array data structure (x and y indices). So... connect(lineEdit, &QLineEdit::textEdited, [this](const QString &str) { OnChanged(x, y, str); }); – e-holder Jan 05 '17 at 18:50