How to change QSlider with double values

My problem is that I just can't get my QSlider to work with double values ​​instead of an integer, because I need to make it return double values ​​in QLineEdit, and also set its own value when I add some value in the edit.

+7
qt qslider
source share
2 answers

When I was a Qt beginner, I started with this tutorial . It is a bit old (it belongs to Qt4.1), but it was good enough to start me!

I put together a simple sample application that can show you where to start ... You might find it useful!

#include <QApplication> #include <QtGui> #include <QVBoxLayout> #include <QSlider> #include <QLabel> class DoubleSlider : public QSlider { Q_OBJECT public: DoubleSlider(QWidget *parent = 0) : QSlider(parent) { connect(this, SIGNAL(valueChanged(int)), this, SLOT(notifyValueChanged(int))); } signals: void doubleValueChanged(double value); public slots: void notifyValueChanged(int value) { double doubleValue = value / 10.0; emit doubleValueChanged(doubleValue); } }; class Test : public QWidget { Q_OBJECT public: Test(QWidget *parent = 0) : QWidget(parent), m_slider(new DoubleSlider()), m_label(new QLabel()) { m_slider->setOrientation(Qt::Horizontal); m_slider->setRange(0, 100); QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(m_slider); layout->addWidget(m_label); connect(m_slider, SIGNAL(doubleValueChanged(double)), this, SLOT(updateLabelValue(double))); updateLabelValue(m_slider->value()); } public slots: void updateLabelValue(double value) { m_label->setText(QString::number(value, 'f', 2)); } private: QSlider *m_slider; QLabel *m_label; }; int main(int argc, char *argv[]) { QApplication a(argc, argv); Test *wid = new Test(); wid->show(); return a.exec(); } #include "main.moc" 
+5
source share

You can simply divide the value of the slider by some constant. For example:

 const int dpi = 10; // Any constant 10^n int slideVal = 57; // Integer value from slider double realVal = double( slideVal / dpi ); // float value 
+3
source share

All Articles