Creating a common slot for multiple instances of QDoubleSpinBox

154 Views Asked by At

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!

3

There are 3 best solutions below

0
m7913d On BEST ANSWER

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:

  1. 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.

  2. Using std::bind:

    connect(ui->horizontalSlider, &QSlider::valueChanged, this /*context*/, std::bind(&MainWindow::ConvertSetSpinBoxValue, this, value, ui->doubleSpinBox));
    
  3. 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

0
G.M. On

Using the new Qt5 signal/slot syntax allows you to connect to a lambda that can capture the QDoubleSpinBox * (untested)...

auto *sb = ui->doubleSpinBox;
connect(ui->horizontalSlider, &QAbstractSlider::valueChanged, this,
        [this, sb](int value)
        {
            this->ConvertSetSpinBoxValue(value, sb);
        });
0
Vasilij On
connect(ui->horizontalSlider, &QSlider::valueChanged, 
[this] (int value) { 
    ConvertSetSpinBoxValue(value, ui->doubleSpinBox); 
});
  1. Please use modern syntax for connections
  2. A lambda should help you