QSlider reporting incorrect value for valueChanged()

I’m trying to connect a QSlider object to a QLineEdit such to enable a user to either specify a value using the slider or direct input into a form. The goal here is when the slider position changes, we update the text in the QLineEdit box and vice versa. However, when I try to report out the value of QSlider->valueChanged(), I’m just getting back a value of 1, regardless of where the slider position is set to. What am I doing incorrectly?

Here is my MWE:

    QSlider* decay_slider = new QSlider(Qt::Horizontal, this);
    decay_slider->setMaximum(11000); // increments of 0.1 years

    QLineEdit* le_decay_time = new QLineEdit(this);
    // Map slider position signal to LineEdit text update
    QSignalMapper* mapper = new QSignalMapper(this);
                     SIGNAL(mapped(const QString&)),
                     SLOT(setText(const QString&)));
    QObject::connect(decay_slider, SIGNAL(valueChanged(int)), mapper, SLOT(map()));

(This is Qt-5.15, if it matters.)

>Solution :

Your call to setMapping hard-codes the value of sliderPosition to the initial version.

Good thing we have lambdas now, so you can replace the entire second paragraph with:

QObject::connect(decay_slider, &QSlider::valueChanged, le_decay_time,
  [=](int value) { le_decay_time->setText(QString::number(value)); });

Leave a Reply