I am trying to create a custom slot that can receive an int and pass it as a double to QDoubleSpinBox.SetValue(double);
But I have a bunch of spinboxes in my UI so I would like to have a single slot that can have a DoubleSpinBox pointer as a parameter like so:
void MainWindow::ConvertSetSpinBoxValue(int value, QDoubleSpinBox * spinbox)
{
double ValToDouble = value;
spinbox->setValue(ValToDouble);
}
and then I can connect a widget that emits a Int returning signal i.e. a QSlider:
connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(ConvertSetSpinBoxValue(int, ui->doubleSpinBox)));
This connect could be repeated and I would simply change the spinbox pointer. But this doesn't work and the connect is discarded at compilation. Any idea? thanks!
As the others pointed out using the (new) Qt5 signals and slots (using function pointers and lambda functions) should solve your problem.
Different methods exist:
Using lambda function:
connect(ui->horizontalSlider, &QSlider::valueChanged, this /*context*/, [this] (int value) {ui->doubleSpinBox->setValue(value);});
Note that the context is useful as it automatically destructs the connection when the context is destructed, but it is probably not needed here as the ui->horizontalSlider
will probably destructed first.
Using std::bind
:
connect(ui->horizontalSlider, &QSlider::valueChanged, this /*context*/, std::bind(&MainWindow::ConvertSetSpinBoxValue, this, value, ui->doubleSpinBox));
Using implicit conversion between signals/slots:
connect(ui->horizontalSlider, &QSlider::valueChanged, ui->doubleSpinBox, &QDoubleSpinBox::SetValue);
Note that the new signal and slot mechanism allows implicit conversion between the signals and slots.
References