Home > database >  QSlider reporting incorrect value for valueChanged()
QSlider reporting incorrect value for valueChanged()

Time:06-11

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->setMinimum(1);
    decay_slider->setMaximum(11000); // increments of 0.1 years
    decay_slider->setTickPosition(QSlider::TicksBothSides);

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

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

CodePudding user response:

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)); });
  • Related