事件过滤器功能使得一个QObject对象可以监视另一个QObject对象中的事件,通过在一个QObject对象中安装事件过滤器,可以在事件到达该对象前捕获事件,从而起到监视该对象的作用。
例如,实现按下按钮时,按钮上的文字为“Key Down”,松开按钮时,按钮上的文字为“Key Up”,创建一个QMainWindow窗口
1. mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class QPushButton;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
bool eventFilter(QObject* watched, QEvent* event);
private:
Ui::MainWindow *ui;
QPushButton* m_button;
};
#endif // MAINWINDOW_H
2. mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QMouseEvent>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_button = new QPushButton("Key Up", this);
m_button->installEventFilter(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if(watched == m_button)
{
if(event->type() == QEvent::MouseButtonPress) //鼠标按下
{
QMouseEvent* mouseEvent = (QMouseEvent*)event;
if(mouseEvent->buttons() & Qt::LeftButton) //左键按下
{
m_button->setText("Left Key Down");
}
else if(mouseEvent->buttons() & Qt::MidButton)
{
m_button->setText("Middle Key Down");
}
else if(mouseEvent->buttons() & Qt::RightButton)
{
m_button->setText("Right Key Down");
}
}
else if(event->type() == QEvent::MouseButtonRelease) //鼠标释放
{
m_button->setText("Key Up");
}
}
//将事件交给上层对话框
return QObject::eventFilter(watched, event);
}