Search code examples
qtrangeqsliderqspinbox

use a created vector as range for QDoubleSpinBox and QSlider


I've created a vector v with 128 elements from -3000 to 3000 and I want to associate it to a QDoubleSpinBox and a QSlider, because dividing 6000 to 128 and setting the QDoubleSpinBox we have always the round problem. So can we set the range and the stepsize both to a QDoubleSpinBox and QSlider with a vector like this?

  std::vector<double> v(128);

  for (int i = 0; i < 128; ++i)
  {
      v[i] = -3000.0 + 6000.0 * (i) / 127.0;
  }

Solution

  • QSlider only operates with int steps, so you'd just need to do the calculation yourself:

    #include <QtGui>
    #include <cmath>
    
    class MyWidget : public QWidget {
      Q_OBJECT
    
    public:
      MyWidget() : QWidget() {
        slider_ = new QSlider;
        slider_->setRange(0, 127);
        connect(slider_, SIGNAL(valueChanged(int)), SLOT(ChangeSpinBox(int)));
    
        box_ = new QDoubleSpinBox;
        box_->setRange(-3000.0, 3000.0);
        connect(box_, SIGNAL(valueChanged(double)), SLOT(ChangeSlider(double)));
    
        QVBoxLayout *layout = new QVBoxLayout;
        layout->addWidget(slider_);
        layout->addWidget(box_);
    
        setLayout(layout);
      }
    private slots:
      void ChangeSpinBox(int sliderValue) {
        if (convertSpinBoxValueToSlider(box_->value()) != sliderValue) {
            box_->setValue((6000.0 * sliderValue / 127.0) - 3000.0);
        }
      }
    
      void ChangeSlider(double spinBoxValue) {
        slider_->setValue(convertSpinBoxValueToSlider(spinBoxValue));
      }
    
    private:
      QSlider *slider_;
      QDoubleSpinBox *box_;
    
      static int convertSpinBoxValueToSlider(double value) {
        return qRound((value + 3000.0) * 127.0 / 6000.0);
      }
    
    };
    
    int main(int argc, char **argv) {
      QApplication app(argc, argv);
      MyWidget w;
      w.show();
      return app.exec();
    }
    
    #include "main.moc"
    

    Or am I not understanding your question?