c++qtqt-signalsslotqsignalmapper

How does QSignalMapper work?


After my post here : Associate signal and slot to a qcheckbox create dynamically I need to associate :

• The signal clicked() when I click on a qCheckBox to my function cliqueCheckBox(QTableWidget *monTab, int ligne, QCheckBox *pCheckBox)

To do so, I have to use QSignalMapper, after two hours of trying to understand how it works, I can't have a good result, here's the code I make, this is obviously wrong :

 QSignalMapper *m_sigmapper = new QSignalMapper(this);
 QObject::connect(pCheckBox, SIGNAL(mapped(QTableWidget*,int, QCheckBox*)), pCheckBox, SIGNAL(clicked()));
 QObject::connect(this, SIGNAL(clicked()), this, SLOT(cliqueCheckBox(QTableWidget *monTab, int ligne, QCheckBox *pCheckBox)));

 m_sigmapper->setMapping(pCheckBox, (monTab,ligne, pCheckBox));
 QObject::connect(m_sigmapper, SIGNAL(clicked()),this, SLOT(cliqueCheckBox(QTableWidget *monTab, int ligne, QCheckBox *pCheckBox)));

Can you explain to me, how QSignalMapper works ? I don't really understand what to associate with :(


Solution

  • QSignalMapper 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. So you can have one like:

    QSignalMapper * mapper = new QSignalMapper(this);
    QObject::connect(mapper,SIGNAL(mapped(QWidget *)),this,SLOT(mySlot(QWidget *)));
    

    For each of your buttons you can connect the clicked() signal to the map() slot of QSignalMapper and add a mapping using setMapping so that when clicked() is signaled from a button, the signal mapped(QWidget *) is emitted:

    QPushButton * but = new QPushButton(this);
    
    QObject::connect(but, SIGNAL(clicked()),mapper,SLOT(map()));
    mapper->setMapping(but, but);
    

    This way whenever you click a button, the mapped(QWidget *) signal of the mapper is emitted containing the widget as a parameter.