QSlider mouse direct jump

后端 未结 12 1726
爱一瞬间的悲伤
爱一瞬间的悲伤 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 16:58

    I needed this too and tried spyke solution, but it's missing two things:

    • inverted appearance
    • handle picking (when the mouse is over the handle, direct jump is not necessary)

    So, here's the reviewed code:

    void MySlider::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()) == false)
      {
        int newVal;
        if (orientation() == Qt::Vertical)
           newVal = minimum() + ((maximum()-minimum()) * (height()-event->y())) / height();
        else
           newVal = minimum() + ((maximum()-minimum()) * event->x()) / width();
    
        if (invertedAppearance() == true)
            setValue( maximum() - newVal );
        else
            setValue(newVal);
    
        event->accept();
      }
      QSlider::mousePressEvent(event);
    }
    

提交回复
热议问题