QT的事件过滤器eventFilter
Qt中的事件过滤器(Event Filter)是一种强大的机制,允许对象拦截并处理其他对象的事件,而无需子类化目标对象。
工作原理:
1、通过installEventFilter()在目标对象上安装过滤器(构造函数中),指定一个监视对象(如父组件)。
this->imp->ui.label->installEventFilter(this);this->imp->ui.label_2->installEventFilter(this); this->imp->ui.label_3->installEventFilter(this);
2、监视对象需重写eventFilter()函数,处理或拦截事件。
bool eventFilter(QObject* watched, QEvent* event) override;
bool CameraDetectionToolEditorWidget::eventFilter(QObject* watched, QEvent* event)
{if (watched == this->imp->ui.label && event->type() == QEvent::Paint)on_TrackingFront();if (watched == this->imp->ui.label_2 && event->type() == QEvent::Paint)on_TrackingTop();if (watched == this->imp->ui.label_3 && event->type() == QEvent::Paint)on_TrackingSide();return QWidget::eventFilter(watched, event);
}
若eventFilter()返回true,事件被拦截,目标对象不会接收到该事件;返回false则事件继续传递。
3、完成后通过removeEventFilter移除过滤器(构造函数中)
this->imp->ui.label->removeEventFilter(this);this->imp->ui.label_2->removeEventFilter(this);this->imp->ui.label_3->removeEventFilter(this);
事件传递顺序:
- 事件先传递给监视对象的
eventFilter()
,再到达目标对象的event()
函数或具体事件处理器(如paintevent)。 - 多个过滤器按安装的逆序执行,第一个返回
true
的过滤器会终止传递。
- 事件先传递给监视对象的
性能考量:
- 避免在
eventFilter()
中执行耗时操作,防止界面卡顿。 - 精确判断
watched
对象和事件类型,减少不必要的处理。
- 避免在