colddie
colddie

Reputation: 1049

QSignalMapper with signal argument and extra argument

I knew that QSignalMapper work well for the condition like this:

QSignalMapper *signalMapper = new QSignalMapper(this);
connect(signalMapper, SIGNAL(mapped(int)), this, SIGNAL(SetSlice(int)));

connect(this->ui->button_1, SIGNAL(slicked()), signalMapper, SLOT(map()));
connect(this->ui->button_2, SIGNAL(clicked()), signalMapper, SLOT(map()));
connect(this->ui->button_3, SIGNAL(clicked()), signalMapper, SLOT(map()));

Now I want to implement 3 sliders all have one SLOT like buttons:

QSignalMapper *signalMapper = new QSignalMapper(this);
connect(signalMapper, SIGNAL(mapped(int)), this, SIGNAL(SetSlice(int)));

connect(this->ui->verticalSlider_1, SIGNAL(valueChanged(int)), signalMapper, SLOT(map()));
connect(this->ui->verticalSlider_2, SIGNAL(valueChanged(int)), signalMapper, SLOT(map()));
connect(this->ui->verticalSlider_3, SIGNAL(valueChanged(int)), signalMapper, SLOT(map()));

As you can see, this is contradictory with the consistent rule between SIGNAL and SLOT. Is there a workaround here? I am using Qt4.

Upvotes: 2

Views: 3693

Answers (1)

Kamil Klimek
Kamil Klimek

Reputation: 13130

QSignalMapper is not about sending arguments from signals to slots but to let signal receiver know "who" was that or what data use. If you need to know both value and sender you either can use some internal class mapping, or use QObject * mapper and then cast QObject * to slider.

QSignalMapper * mapper = new QSignalMapper(this);
connect(mapper, SIGNAL(map(QWidget *)), this, SLOT(SetSlice(QWidget *)));

mapper->setMapping(this->ui->verticalSlider_1, this->ui->verticalSlider_1);
mapper->setMapping(this->ui->verticalSlider_2, this->ui->verticalSlider_2);
mapper->setMapping(this->ui->verticalSlider_3, this->ui->verticalSlider_3);

And here's slot body:

void YourClass::SetSlice(QWidget *wgt)
{
    QSlider * slider = qobject_cast<QSlider *>(wgt);

    if(slider) {
        SetSlice(slider->value());
    }
}

Upvotes: 3

Related Questions