QT application programming: QSlider sets the scroll block to position the mouse click

1. Environmental introduction

QT version: 5.12.6

2. Implementation method

Drag a horizontalSlider control on the UI interface to facilitate testing.

Overload the eventFilter function in the main interface class to intercept mouse events.

//主线程
class Widget : public QWidget
{
    Q_OBJECT

public:
    ....................
private slots:
    ....................

protected:
    bool eventFilter(QObject *obj, QEvent *event);
private:
    Ui::Widget *ui;
};


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->horizontalSlider_2->installEventFilter(this);
    ...................略.................................
}


bool Widget::eventFilter(QObject *obj, QEvent *event)
{
    //解决QSlider点击不能到鼠标指定位置的问题
    if(obj==ui->horizontalSlider_2)
    {
        if (event->type()==QEvent::MouseButtonPress)           //判断类型
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)	//判断左键
            {
               int value = QStyle::sliderValueFromPosition(ui->horizontalSlider_2->minimum(), ui->horizontalSlider_2->maximum(), mouseEvent->pos().x(), ui->horizontalSlider_2->width());
               ui->horizontalSlider_2->setValue(value);
            }
        }
    }
    return QObject::eventFilter(obj,event);
}

 

Guess you like

Origin blog.csdn.net/xiaolong1126626497/article/details/110453097