Qt NativeEventFilter

NativeEventFilter,本地事件过滤器,在Qt中,当需要对系统消息或者自定义消息进行处理时会用到。相关的有QAbstractNativeEventFilter类和两个函数(installNativeEventFilter、removeNativeEventFilter)

一 QAbstractNativeEventFilter

该类比较简单,纯虚类,只有一个虚接口:

virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) = 0

实际中一般是在QApplication层面对系统消息进行处理。有两种方式:

1、从QApplication派生出一个类,并且继承QAbstractNativeEventFilter,实现nativeEventFilter接口

demo:

class MyApp : public QApplication , public QAbstractNativeEventFilter 
{....};

2、单写一个QAbstractNativeEventFilter一个子类,然后在QApplication安装该过滤器即可,涉及QApplication的两个函数:

void installNativeEventFilter(QAbstractNativeEventFilter *filterObj)
void removeNativeEventFilter(QAbstractNativeEventFilter *filterObject)

demo:

#include <QApplication>
#include <QAbstractNativeEventFilter>

class MyAppNativeEventFilter  : public QAbstractNativeEventFilter 
{
    virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override;
};

int main(int argc,   char* argv [])
{
    QApplication app(argc, argv);
    MyAppNativeEventFilter filter;
    app.installNativeEventFilter(&filter);
    return app.run();
}

二 nativeEventFilter接口实现

Qt assistant上有一些事例。

例如windows上

virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *) override
{
    if(eventType == "windows_generic_MSG" || eventType == "windows_dispatcher_MSG")
    {
        MSG* pMsg = reinterpret_cast<MSG*>(message);
        if(pMsg->message == WM_COPYDATA)
        {
            qDebug()<<"demo";
        }
    }
    return false; // 注意返回值
};

1、文档上对nativeEventFilter的返回值有说明:

In your reimplementation of this function, if you want to filter the message out, i.e. stop it being handled further, return true; otherwise return false.

2、不同系统上eventType不同

X11 为 "xcb_generic_event_t"

macOS 为 "mac_generic_NSEvent"

windows  为 "windows_generic_MSG" 和 "windows_dispatcher_MSG"

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值