1. Introducción medioambiental
Versión QT: 5.12.6
2. Método de implementación
Arrastre un control deslizante horizontal en la interfaz de IU para facilitar las pruebas.
Sobrecargue la función eventFilter en la clase de interfaz principal para interceptar eventos del mouse.
//主线程
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);
}