QSlider 在点击非滑块部分时,不会直接到点击位置,而是一步一步执行,在项目中使用时会感觉不流畅。可以通过改变QSlider的鼠标点击事件(mousePressEvent)和鼠标移动事件(mouseMoveEvent)解决。
使用原QSlider
如UI中使用verticalSlider,MySliderUI.h 头文件:
class MySliderUI : public QWidget
{
Q_OBJECT
public:
explicit MySliderUI(QWidget *parent = 0);
~MySliderUI();
protected:
bool eventFilter(QObject *obj, QEvent *event);
private:
Ui::EpsSliderUI *ui;
};
MySliderUI.cpp
MySliderUI::MySliderUI(QWidget *parent) :
QWidget(parent)
{
ui->slider->installEventFilter(this);
}
添加事件过滤,对QSlider的事件重新处理。
bool MySliderUI::eventFilter(QObject *obj, QEvent *event)
{
if( obj == ui->slider)
{
if (event->type() == QEvent::MouseButtonPress)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::LeftButton)
{
ui->slider->event(event);
double pos = mouseEvent->pos().y() / (double)ui->slider->height();
int value = pos * (ui->slider->maximum() - ui->slider->minimum())
+ ui->slider->minimum()+0.5;
ui->slider->setValue(value);
return true;
}
}
else if (event->type() == QEvent::MouseButtonDblClick)
{
return true;
}
else if (event->type() == QEvent::MouseMove)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
ui->slider->event(event);
double pos = mouseEvent->pos().y() / (double)ui->slider->height();
int value = pos * (ui->slider->maximum() - ui->slider->minimum())
+ ui->slider->minimum()+0.5;
ui->slider->setValue(value);
return true;
}
}
return QObject::eventFilter(obj,event);
}
继承QSlider,重写事件函数
头文件文章来源:https://www.toymoban.com/news/detail-606026.html
class MySlider : public QSlider
{
Q_OBJECT
public:
MySlider(QWidget *parent = nullptr);
~MySlider();
protected:
void mousePressEvent(QMouseEvent *event); //单击
void mouseMoveEvent(QMouseEvent *event);
};
实现文件文章来源地址https://www.toymoban.com/news/detail-606026.html
#include "myslider.h"
#include <QMouseEvent>
MySlider::MySlider(QWidget *parent)
:QSlider (parent)
{
}
MySlider::~MySlider()
{
}
void MySlider::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) //判断左键
{
//注意应先调用父类的鼠标点击处理事件,这样可以不影响拖动的情况
QSlider::mousePressEvent(event);
double pos = ((double)height() - event->pos().y()) / (double)height();
int value = pos * (maximum() - minimum()) + minimum();
setValue(value);
}
}
void MySlider::mouseMoveEvent(QMouseEvent *event)
{
//注意应先调用父类的鼠标点击处理事件,这样可以不影响拖动的情况
QSlider::mouseMoveEvent(event);
double pos = ((double)height() - event->pos().y()) / (double)height();
int value = pos * (maximum() - minimum()) + minimum();
setValue(value);
}
到了这里,关于Qt滑动条解决点击和拖动问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!