Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Qt event filter

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

这篇文章主要介绍"Qt事件过滤器怎么实现"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"Qt事件过滤器怎么实现"文章能帮助大家解决问题。

1.事件过滤器void QObject::installEventFilter(QObject *filterObj)bool eventFilter(QObject *obj, QEvent *event);

Qt的事件过滤由以上两个方法实现,首先安装一个事件过滤器,然后重写bool eventFilter(QObject *obj, QEvent *event)。

filterObj表示事件筛选器对象,它接收发送到此QObject对象的所有事件。筛选器可以停止事件,也可以将事件转发给此QObject对象。事件过滤器filterObj通过它的eventFilter()函数接收事件。

eventFilter()有返回值。

如果返回true,表示事件过滤,不会发送到对象本身。

如果返回false,表示事件未过滤,会通过event()方法将事件分发到对象。

返回给基类进行处理,例:return QObject::eventFilter(obj, event)。

2.示例

一个label,当鼠标进入的时候变成红色,鼠标离开的时候变为黑色

#include "widget.h"#include "ui_widget.h" QString redStyle = "QLabel#label{color:#FF0000}"; QString blackStyle = "QLabel#label{color:#000000}"; Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget){ ui->setupUi(this); ui->label->installEventFilter(this);} Widget::~Widget(){ delete ui;} bool Widget::eventFilter(QObject *obj, QEvent *event){ if(obj == ui->label) { //鼠标进入的时候 if (event->type() == QEvent::Enter) { ui->label->setText("我是红色"); ui->label->setStyleSheet(redStyle); return true; } else if(event->type() == QEvent::Leave) //鼠标离开 { ui->label->setText("我是黑色"); ui->label->setStyleSheet(blackStyle); return true; } return false;//别的事件会传给label对象 } // standard event processing return QWidget::eventFilter(obj, event);}

上述代码,假如我们不使用事件过滤器,我们就无法实现上述鼠标进入、离开功能,只能自己继承QLabel,重写鼠标进入、离开事件。

3.简单分析

自定义一个label类继承QLabel,查看事件的处理顺序,以及过滤器是否起作用。

#ifndef WLABEL_H#define WLABEL_H #include #include class WLabel : public QLabel{public: WLabel(QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags()); protected: virtual bool event(QEvent *e); virtual void enterEvent(QEvent *event); virtual void leaveEvent(QEvent *event); }; #endif // WLABEL_H #include "wlabel.h"#include WLabel::WLabel(QWidget *parent, Qt::WindowFlags f) : QLabel(parent,f){ } bool WLabel::event(QEvent *e){ if(e->type() == QEvent::Enter) { qDebug()

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report