QT::事件过滤

事件处理的方式

1.重新实现对象的特定事件处理函数,例如mousePressEvent、keyPressEvent 、showEvent等,处理完毕后将事件交给父类;

2.重新实现event函数,处理完毕后将事件交给父类;

3.在对象上安装事件过滤器,让其他对象控制此对象的事件行为;

4.给主程序QCoreApplication安装事件过滤器,在调用notify进行事件分发之前,会根据过滤器判断对事件的处理(例如:丢弃);

5.子类化QCoreApplication,重新实现notify事件分发函数;
事件过滤器
通过调用过滤器对象的QObject::installEventFilter()函数,为目标对象设置一个事件过滤器,
就可在过滤器对象的QObject::eventFilter()函数中处理发往目标对象的事件。
一个事件过滤器在目标对象收到事件之前处理事件,这使得过滤器对象在需要的时候可以检查并丢弃事件。
可以调用 QObject::removeEventFilter()来移除已经安装的事件过滤器。
Qt::postEvent              同步分发事件
Qt::sendEvent              异步分发事件
Qt::QueuedConnection 同步分发消息 Qt::DirectConnection 异步分发消息
方法一:
//安装事件过滤器

ui->textEdit->installEventFilter(this);
//过滤事件 bool MainWindow::eventFilter(QObject *obj, QEvent *e) { if(obj == ui->textEdit) { if(e->type() == QEvent::Wheel) { QWheelEvent* w = static_cast<QWheelEvent *>(e); if(w->delta() > 0) ui->textEdit->zoomIn(); else ui->textEdit->zoomOut(); }else return false; } else return QWidget::eventFilter(obj, e); }

方法二:自定义 MyQApplication 继承 QApplication 实现 notify 函数
class MyApplication : public QApplication
{
public:

    MyApplication(int argc, char **argv) : QApplication(argc,argv) {}
    virtual bool notify(QObject *, QEvent *);
};

bool MyApplication::notify(QObject *receiver, QEvent *event)
{
    if(event->type() == QMouseEvent::MouseButtonPress)
    {
        qDebug() << "get all mouse press event";
        return true;
    }

    return QApplication::notify(receiver,event);
}
原文地址:https://www.cnblogs.com/osbreak/p/14342667.html