c++qtqslider

How to create a QSlider with a non-linear scale?


Is there a simple way to implement a non-linear scale to a QSlider? I want to implement a logarithmic scale to it.

The only workaround I am thinking of is manipulating the value change signals outside of the class.


Solution

  • I implemented a LogSlider, with a scale factor and it worked well.

    class LogSlider : public QSlider {
      Q_OBJECT
     public:
      explicit LogSlider(QWidget* parent = nullptr, scale = 1000) : QSlider(parent) : m_scale(scale) {
        QObject::connect(this, &QSlider::valueChanged, this,
                         &LogSlider::onValueChanged);
        setOrientation(Qt::Horizontal);
      }
    
      void setNaturalMin(double min) { setMinimum(int(log10(min) * m_scale)); }
      void setNaturalMax(double max) { setMaximum(int(log10(max) * m_scale)); }
      void setNaturalValue(double value) { setValue(int(log10(value) * m_scale)); }
    
     private slots:
      void onValueChanged(double value) {
        emit naturalValueChanged(std::pow(10, (value / m_scale));
      }
    
     signals:
      void naturalValueChanged(double value);
    
     private:
      double m_scale;
    };