Use created vector as a range for QDoubleSpinBox and QSlider

I created a vector v with 128 elements from -3000 to 3000, and I want to associate it with QDoubleSpinBoxand QSlider, since dividing 6000 by 128 and installing QDoubleSpinBox, we always have a round problem. So, can we set the range and steps both on QDoubleSpinBoxand on QSliderwith such a vector?

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

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

QSlideronly works with steps int, so you 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 I do not understand your question?

+2
source

, . X , X + 1, X. : 0 5 . ? 5. [0,2,4,6,8,10] = 6. , 129 128.

, 6000/128 = 48,875 . QDoubleSpinBox

QDoubleSpinBox::setRange(-3000.0,3000.0);
QDoubleSpinBox::setSingleStep(48.875);

QSlider, . , 1000.

QSlider::setRange(-3000000,3000000);
QSlider::setSingleStep(48875);

, 1000 , .

0

All Articles