QT5: 事件过滤.

虽然能够用event拦截事件,可是有的时候咱们的应用中用到了不少的组件,或者咱们本身实现了一个组件继承了不少其余的组件,咱们要想经过event拦截事件,就变得很困难了,必须重写全部的event()函数,异常的麻烦.ide

可是QT5给咱们提供了事件过滤器,该事件过滤器被安装后起做用于事件发生以后事件分配以前(event()).函数

(public: vritual) bool Object::eventFilter(QObject* watched, QEvent* event);

该函数接受一个QObject* 的参数和一个QEvent* 参数,且该函数返回一个bool类型,若是咱们拦截掉了该event,那么返回true.this

若是咱们想要事件继续传播,那么返回false.spa

其中第一个参数QObject*类型的:是咱们安装了事件过滤器的对象,第二个就是事件咯.code

全部组件都是QObject的子类记住!!!!!!!!!!!!对象

看代码吧:继承

 #include <QWidget>
#include <QObject>
#include <QEvent>
#include <QMouseEvent>
#include <QDebug>
class Lable : public QWidget
{
public:
    inline Lable()
    {
        this->installEventFilter(this);//注意这里给本身安装事件过滤器.
    }
    ~Lable ()=default;
    virtual bool eventFilter(QObject* watched, QEvent* event)override //事件过滤器. 
    {
        if(watched == this){
            if(event->type() == QEvent::MouseButtonPress){
                qDebug()<<"eventFilter";
            }
        }
        return false;
    }
protected:
    virtual void mousePressEvent(QMouseEvent* mouseEvent)override
    {
        qDebug()<<"mousePressEvent";
        //处理了事件.
        //由于mouseEvent默认是accept的.
    }
    virtual bool event(QEvent* event)override //这里也没有处理该事件.
    {
        if(event->type() == QEvent::MouseButtonPress){
            qDebug()<<"event";
        }
        return this->QWidget::event(event);//由父类的同名函数再次进行事件分配.
    }
};
class EventFilter : public QObject
{
public:
    EventFilter(QObject* watched, QObject* parent = nullptr):QObject(parent),watched_(watched){}
    virtual bool eventFilter(QObject* w, QEvent* event)override //发生的全部事件首先通过该事件过滤器.
    {
        if(w = this->watched_){
            if(event->type() == QEvent::MouseButtonPress){
                qDebug()<<"Application EventFilter";
            }
        }
        return false; //返回fasle标明并无处理该事件.而后该事件传递给了Lable中的eventFilter.
    }
private:
    QObject* watched_;
};

 

 #include "mainwindow.h"
#include <QApplication>
#include <memory>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Lable label;
    std::shared_ptr<EventFilter> event(new EventFilter(&label, &label));
    a.installEventFilter(event.get());
    label.show();
    return a.exec();
}

上面的例子输出是:事件

Application EventFilter
eventFilter
event
mousePressEventget

 

咱们再来了解一下安装事件过滤器的函数:it

(public: virtual) bool QObject::installEventFilter(QObject* eventFilter);

其中eventFilter就是咱们想要安装的时间过滤器.

installEventFilter()是QObject的函数,而QApplication和QCoreApplication都是QObject的子类,所以咱们就能够给本身的应用程序安装全局的事件过滤器.该应用程序级别的事件过滤器被安装之后,全部其余组件的事件过滤器发挥做用都在它的后面.

相关文章
相关标签/搜索