QSlider mouse direct jump

后端 未结 12 1773
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 16:27

Instead of stepping when the user clicks somewhere on the qslider I want to make the slider jump to that position. How can this be implemented ?

12条回答
  •  轮回少年
    2020-12-23 17:21

    My final implementation based on surrounding comments:

    class ClickableSlider : public QSlider {
    public:
        ClickableSlider(QWidget *parent = 0) : QSlider(parent) {}
    
    protected:
        void ClickableSlider::mousePressEvent(QMouseEvent *event) {
          QStyleOptionSlider opt;
          initStyleOption(&opt);
          QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
    
          if (event->button() == Qt::LeftButton &&
              !sr.contains(event->pos())) {
            int newVal;
            if (orientation() == Qt::Vertical) {
               double halfHandleHeight = (0.5 * sr.height()) + 0.5;
               int adaptedPosY = height() - event->y();
               if ( adaptedPosY < halfHandleHeight )
                     adaptedPosY = halfHandleHeight;
               if ( adaptedPosY > height() - halfHandleHeight )
                     adaptedPosY = height() - halfHandleHeight;
               double newHeight = (height() - halfHandleHeight) - halfHandleHeight;
               double normalizedPosition = (adaptedPosY - halfHandleHeight)  / newHeight ;
    
               newVal = minimum() + (maximum()-minimum()) * normalizedPosition;
            } else {
                double halfHandleWidth = (0.5 * sr.width()) + 0.5;
                int adaptedPosX = event->x();
                if ( adaptedPosX < halfHandleWidth )
                      adaptedPosX = halfHandleWidth;
                if ( adaptedPosX > width() - halfHandleWidth )
                      adaptedPosX = width() - halfHandleWidth;
                double newWidth = (width() - halfHandleWidth) - halfHandleWidth;
                double normalizedPosition = (adaptedPosX - halfHandleWidth)  / newWidth ;
    
                newVal = minimum() + ((maximum()-minimum()) * normalizedPosition);
            }
    
            if (invertedAppearance())
                setValue( maximum() - newVal );
            else
                setValue(newVal);
    
            event->accept();
          } else {
            QSlider::mousePressEvent(event);
          }
        }
    };
    

提交回复
热议问题