Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)); });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading