基于QT5.14.0版本
一、什么是事件过滤器
事件过滤器是Qt中强大的事件处理机制,允许一个对象监视另一个对象的事件流。通过事件过滤器,你可以在事件到达目标对象之前拦截、修改或丢弃事件。

工作原理
1.对象A安装事件过滤器到对象B
2.当事件发送到对象B时,Qt会先调用对象A的eventFilter()方法
3.对象A决定是否处理该事件
4.如果返回true,事件被拦截不再传递
5.如果返回false,事件继续传递给对象B
二、事件过滤器使用指南
1. 基本使用步骤
// 1. 在监视对象中重写eventFilter方法
bool MyFilter::eventFilter(QObject *watched, QEvent *event) {
if (watched == targetObject && event->type() == QEvent::KeyPress) {
// 处理逻辑
return true; // 拦截事件
}
return false; // 继续传递事件
}
// 2. 安装事件过滤器
targetObject->installEventFilter(myFilterObject);
2. 移除事件过滤器
targetObject->removeEventFilter(myFilterObject);
三、常用事件类型详解
1. 鼠标事件
QMouseEvent
bool eventFilter(QObject *watched, QEvent *event) {
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
qDebug() << "Pressed at:" << mouseEvent->pos();
// 获取鼠标按键
if (mouseEvent->button() == Qt::LeftButton) {
// 左键处理
}
}
return false;
}
常用事件类型:
MouseButtonPress:鼠标按下
MouseButtonRelease:鼠标释放
MouseButtonDblClick:鼠标双击
MouseMove:鼠标移动
2. 键盘事件
QKeyEvent
bool eventFilter(QObject *watched, QEvent *event)


1万+

被折叠的 条评论
为什么被折叠?



