QT中的事件过滤器及常见事件介绍

基于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) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值