事件过滤器

Qt中的事件过滤器可以用来对一些控件对象进行事件过滤和处理,其对应接口为 void QObject::installEventFilter(QObject *filterObj)
其中 filterObj是派生自 QObject的类对象,具体的过滤事件处理是在对应的 bool eventFilter(QObject* obj, QEvent* event) override中执行的。

以过滤窗口的关闭事件为例,

1、 过滤器派生类:

filterObj定义
// .h 头文件
class WindowEventFilter :public QObject
{
    Q_OBJECT
protected:
    bool eventFilter(QObject* obj, QEvent* event) override;
};


// .cpp 需要过滤的事件
bool WindowEventFilter::eventFilter(QObject* obj, QEvent* event)
{
    // 对关闭窗口的事件进行过滤处理
    if (event->type() == QEvent::Close)
    {
        QMainWindow* win = qobject_cast<QMainWindow*>(obj);
        if (win)
        {
            event->ignore();
            win->hide();

            // 表示已经处理,将被过滤,不再继续传递
            return true; 
        }
    }

    // 未处理的事件继续路由,或返回false
    return QObject::eventFilter(obj, event);
}

2、窗口安装使用对应的事件过滤器

QMainWindow对象中安装
QMainWindow* m_pWin = new QMainWindow();
WindowEventFilter* filter = new WindowEventFilter();

//QMainWindow 安装事件过滤器,从而实现对需要的事件进行过滤处理
m_pWin->installEventFilter(filter);


// 如果需要移除对应的事件过滤器:
m_pWin->removeEventFilter(filter);

【注意】

  • 事件过滤器能够接收所有发送到该对象(m_pWin)的事件.
  • 如果事件过滤器需要对某个事件进行过滤,需要返回false,将阻止事件继续向前传递;否则返回false将会让事件继续向前传递。
  • 如果同一个对象上安装了多个事件过滤器,最后一个安装的事件过滤器将会被先激活使用。
  • 安装事件过滤器的对象和事件过滤器对象需要在同一个现成中,否则将不会生效
  • 移除事件过滤器是安全的,在事件正在触发的过程中、对象未安装这个事件过滤器的时候都可以调用。

posted @ 2025-06-30 12:02  Jeffxue  阅读(50)  评论(0)    收藏  举报