您可以使用 C++11 lambdas 来解决这个问题。创建一个新的通用“任何事物的事件”QObject,它通过您指定的 lambda 传递其过滤。然后使用所需的逻辑将此通用对象添加到您的显示小部件。例如:
通用-qevent-filter.hpp:
#pragma once
class GenericQEventFilter : public QObject
{
Q_OBJECT
public:
GenericQEventFilter(QObject *parent, std::function<bool (QObject *obj, QEvent *event)> event_filter_f);
std::function<bool (QObject *obj, QEvent *event)> event_filter_f;
protected:
bool eventFilter(QObject *obj, QEvent *event);
};
通用-qevent-filter.cpp:
#include "generic-qevent-filter.hpp"
GenericQEventFilter::GenericQEventFilter(QObject *parent,
std::function<bool (QObject *obj, QEvent *event)> event_filter_f)
: QObject(parent), event_filter_f(event_filter_f)
{
}
bool GenericQEventFilter::eventFilter(QObject *obj, QEvent *event)
{
return this->event_filter_f(obj, event);
}
您在代码中使用它,如下所示:
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent)
{
ui = new Ui_MainWindow();
ui->setupUi(this); // Initialise widgets
this->wire_up_gui(); // Connect signals and slots
ui->displayWidget->installEventFilter(new GenericQEventFilter(this, [&] (QObject *obj, QEvent *event) {
if(event->type() == QEvent::Paint) {
paint_display_widget(obj, event);
return true;
}
return false;
}));
}