Search code examples
c++qtqsignalmapper

How to map to overload Qt slot


I want to overload a Qt SLOT to either react to an emitted clicked() SIGNAL from a QPushButton or a stateChanged(int) SIGNAL from a QCheckBox (since there is no SIGNAL that emits when the checkbox is checked only).

So these are my two SLOTs.

void Widget::sendCom(QString data)
{
    std::cout << "In scope of sendCom"<< std::endl;
}
void Widget::sendCom(QString data, int state)
{
    std::cout << "In scope of overloaded sendCom: " << std::endl;
}

With widget->createButton(SLOT(sendCom(QString), data); i call the following and the mapping works fine.

void Widget::createButton(const char *member, QString &data)
{
    QPushButton *button = new QPushButton(this);
    signalMapper = new QSignalMapper(this);
    signalMapper->setMapping(button, data);
    connect(signalMapper, SIGNAL(mapped(QString)), this, member);
    connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
    ...
}


void Widget::createCheckBox(const char *member, QString &data)
{
}

with widget->createCheckBox(SLOT(QString, int), data) i want to pass in ChechBox's state to the overloaded Widget::sendCom(QString data, int state)as well. How has the mapping to be done?


Solution

  • According to the documentation QSignalMapper only manages parameterless signals. You could derive an new class from QCheckBox where you connect the stateChanged(int) SIGNAL to a corresponding slot in the class where you emit a setChecked() or a setUnchecked() SIGNAL which can be handled by a QSignalMapper.