QSlider mouse direct jump

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

    The answer of Massimo Callegari is almost right, but the calculation of newVal ignores the slider handle width. This problem comes up when you try to click near the end of the slider.

    The following code fixes this for horizontal sliders

    double halfHandleWidth = (0.5 * sr.width()) + 0.5; // Correct rounding
    int adaptedPosX = event->x();
    if ( adaptedPosX < halfHandleWidth )
            adaptedPosX = halfHandleWidth;
    if ( adaptedPosX > width() - halfHandleWidth )
            adaptedPosX = width() - halfHandleWidth;
    // get new dimensions accounting for slider handle width
    double newWidth = (width() - halfHandleWidth) - halfHandleWidth;
    double normalizedPosition = (adaptedPosX - halfHandleWidth)  / newWidth ;
    
    newVal = minimum() + ((maximum()-minimum()) * normalizedPosition);
    

提交回复
热议问题