之前在网上看到重写事件的方法, 如下
void QComboBox::wheelEvent(QWheelEvent *e) {
/*
屏蔽 QComboBox 鼠标滚动
*/
}
void QAbstractSpinBox::wheelEvent(QWheelEvent *e) {
/*
屏蔽 QAbstractSpinBox 鼠标滚动
*/
}
说是直接在主窗体的main.cpp中加入即可屏蔽鼠标滚动,实测不行
这种得分别继承QComboBox和QAbstractSpinBox来自定义控件过滤滚动事件才行,要简单使用的话有点麻烦
事件过滤的方法
我使用了事件过滤方法来实现,不需要重写类
头文件
bool eventFilter(QObject *obj, QEvent *event);
实现
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
// 安装事件过滤器
foreach (QAbstractSpinBox* sb, this->findChildren<QAbstractSpinBox*>())
{
sb->installEventFilter(this);
}
foreach (QComboBox* cb, this->findChildren<QComboBox*>())
{
cb->installEventFilter(this);
}
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
// 屏蔽 spinbox 和 combobox 的滚轮事件
if(obj->inherits("QAbstractSpinBox")||obj->inherits("QComboBox")) {
if(event->type() == QEvent::Wheel) return true;
}
return QMainWindow::eventFilter(obj, event);
}