QSlider mouse direct jump

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

    The following code is actually a hack, but it works fine without sub-classing QSlider. The only thing you need to do is to connect QSlider valueChanged signal to your container.

    Note1: You must set a pageStep > 0 in your slider

    Note2: It works only for an horizontal, left-to-right slider (you should change the calculation of "sliderPosUnderMouse" to work with vertical orientation or inverted appearance)

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
    
        // ...
        connect(ui->mySlider, SIGNAL(valueChanged(int)),
                this, SLOT(mySliderValueChanged(int)));
       // ...
    }
    
    
    void MainWindow::mySliderValueChanged(int newPos)
    {
        // Make slider to follow the mouse directly and not by pageStep steps
        Qt::MouseButtons btns = QApplication::mouseButtons();
        QPoint localMousePos = ui->mySlider->mapFromGlobal(QCursor::pos());
        bool clickOnSlider = (btns & Qt::LeftButton) &&
                             (localMousePos.x() >= 0 && localMousePos.y() >= 0 &&
                              localMousePos.x() < ui->mySlider->size().width() &&
                              localMousePos.y() < ui->mySlider->size().height());
        if (clickOnSlider)
        {
            // Attention! The following works only for Horizontal, Left-to-right sliders
            float posRatio = localMousePos.x() / (float )ui->mySlider->size().width();
            int sliderRange = ui->mySlider->maximum() - ui->mySlider->minimum();
            int sliderPosUnderMouse = ui->mySlider->minimum() + sliderRange * posRatio;
            if (sliderPosUnderMouse != newPos)
            {
                ui->mySlider->setValue(sliderPosUnderMouse);
                return;
            }
        }
        // ...
    }
    

提交回复
热议问题