#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QDebug>
class EventFilter : public QObject {
Q_OBJECT
public:
explicit EventFilter(QObject *parent = nullptr) : QObject(parent) {}
protected:
bool eventFilter(QObject *watched, QEvent *event) override {
if (watched->isWidgetType() && event->type() == QEvent::MouseButtonPress) {
qDebug() << "Mouse button pressed on widget:" << watched;
return true; // 返回true表示事件已被处理
}
return false; // 返回false表示事件未被处理,继续传递
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget window;
window.setWindowTitle("Event Filter Example");
window.setGeometry(100, 100, 300, 200);
QPushButton button("Click Me!", &window);
button.setGeometry(100, 50, 100, 30);
EventFilter eventFilter; // 创建事件过滤器对象
button.installEventFilter(&eventFilter); // 安装事件过滤器
window.show();
return app.exec();
}
#include "main.moc"
没有合适的资源?快使用搜索试试~ 我知道了~
Qt事件过滤器Demo
共3个文件
user:1个
pro:1个
cpp:1个
1 下载量 2 浏览量
2023-10-14
11:16:09
上传
评论
收藏 4KB ZIP 举报
温馨提示
Qt事件过滤器(Event Filter)允许你在Qt应用程序中捕捉和处理事件,而无需修改原始的事件处理函数。使用事件过滤器,你可以在整个应用程序中截获和处理特定类型的事件,而不仅仅局限于单个控件。以下是Qt事件过滤器的使用说明和一个示例: + **使用说明:** 1. **安装事件过滤器:** 使用 `QObject::installEventFilter(QObject *filterObj)` 函数安装事件过滤器。这个函数将事件过滤器对象安装到指定的QObject上。 2. **重载事件过滤器函数:** 在事件过滤器类中,需要重载 `QObject::eventFilter(QObject *watched, QEvent *event)` 函数。这个函数将会在被安装事件过滤器的对象上的所有事件发生时被调用。 3. **处理特定类型的事件:** 在事件过滤器函数中,你可以通过 `event->type()` 检查事件的类型,并根据需要处理事件。
资源推荐
资源详情
资源评论
收起资源包目录
9_3.zip (3个子文件)
9_3
9_3.pro.user 23KB
main.cpp 1KB
9_3.pro 1KB
共 3 条
- 1
资源评论
三雷科技
- 粉丝: 3w+
- 资源: 100
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功