当前位置: 首页 > news >正文

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);

  1. 事件传递顺序

    • 事件先传递给监视对象的eventFilter(),再到达目标对象的event()函数或具体事件处理器(如paintevent)。
    • 多个过滤器按安装的逆序执行,第一个返回true的过滤器会终止传递。
  2. 性能考量

    • 避免在eventFilter()中执行耗时操作,防止界面卡顿。
    • 精确判断watched对象和事件类型,减少不必要的处理。
http://www.dtcms.com/a/268951.html

相关文章:

  • 【1】从零构建Vue3响应式系统:基于TDD的完整实现
  • 【kafka-python使用学习笔记2】Python操作Kafka之环境准备(2)亲测有效有图有真相
  • Kotlin编写Android爬虫教程
  • ICME 2025 | 火山引擎在国际音频编码能力挑战赛中夺得冠军
  • 主机安全-开源HIDS字节跳动Elkeid使用
  • MongoDB与Spring Boot完整使用指南
  • Oracle注释详解
  • MIL-STD-1553B总线
  • 【Pandas】pandas DataFrame boxplot
  • ch04 部分题目思路
  • Logseq 插件开发实战四:发布到官方插件市场
  • 【VSCode 插件离线安装包下载方法分享】
  • 【PyTorch】PyTorch中torch.nn模块的循环层
  • Microsoft Visual Studio离线安装(以2022/2019为例)
  • Python脚本保护工具库之pyarmor使用详解
  • Redis常用数据结构以及多并发场景下的使用分析:list类型
  • Qt的第一个程序(2)
  • Karmada Multi-Ingress(MCI)技术实践
  • verilog中timescale指令的使用
  • javaweb———html
  • 【taro react】 ---- RuiVerifySlider 行为验证码之滑动拼图使用【天爱验证码 tianai-captcha 】实现
  • android ui thread和render thread
  • 上海新华医院奉贤院区:以元宇宙技术重构未来医疗生态
  • RAG 之 Prompt 动态选择的三种方式
  • 华为OD机试 2025B卷 - 小明减肥(C++PythonJAVAJSC语言)
  • 编辑器Vim的快速入门
  • Session的工作机制及安全性分析
  • Qt(信号槽机制)
  • 解数独(C++版本)
  • 永磁同步电机PMSM的无传感器位置控制