How to add a tick mark to a slider if it cannot inherit QSlider

后端 未结 3 1736
忘掉有多难
忘掉有多难 2021-01-07 03:30

I have a Qt dialog and there is a slider in it, when the dialog is initialized the slider will be set a value. In order to remind the user what is the default value, I want

3条回答
  •  梦毁少年i
    2021-01-07 03:33

    I'm not clear why you can't derive a control from QSlider. You can still treat it like a QSlider, just override the paintEvent method. The example below is pretty cheesy, visually speaking, but you could use the methods from QStyle to make it look more natural:

    #include 
    
    class DefaultValueSlider : public QSlider {
      Q_OBJECT
    
     public:
      DefaultValueSlider(Qt::Orientation orientation, QWidget *parent = NULL)
        : QSlider(orientation, parent),
          default_value_(-1) {
        connect(this, SIGNAL(valueChanged(int)), SLOT(VerifyDefaultValue(int)));
      }
    
     protected:
      void paintEvent(QPaintEvent *ev) {
        int position = QStyle::sliderPositionFromValue(minimum(),
                                                       maximum(),
                                                       default_value_,
                                                       width());
        QPainter painter(this);
        painter.drawLine(position, 0, position, height());
        QSlider::paintEvent(ev);
      }
    
     private slots:
      void VerifyDefaultValue(int value){
        if (default_value_ == -1) {
          default_value_ = value;
          update();
        }
      }
    
     private:
      int default_value_;
    };
    
    int main(int argc, char *argv[]) {
      QApplication app(argc, argv);
    
      DefaultValueSlider *slider = new DefaultValueSlider(Qt::Horizontal);
      slider->setValue(30);
    
      QWidget *w = new QWidget;
      QVBoxLayout *layout = new QVBoxLayout;
      layout->addWidget(slider);
      layout->addStretch(1);
      w->setLayout(layout);
    
      QMainWindow window;
      window.setCentralWidget(w);
      window.show();
    
      return app.exec();
    }
    
    #include "main.moc"
    

提交回复
热议问题