qt部件的事件过滤器

本文介绍了如何在Qt中创建一个名为MyWidget的自定义QWidget子类,展示图像并实现鼠标移动事件过滤器,用于实时响应鼠标位置变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>

class QLabel;
class MyWidget : public QWidget
{
    Q_OBJECT
public:
    explicit MyWidget(QWidget *parent = nullptr);
protected:
    bool eventFilter(QObject *obj, QEvent *event) override;
private:
    QLabel *top_show_area_;
    QLabel *image_show_area_;
};

#endif // MYWIDGET_H
#include "mywidget.h"
#include <QLabel>
#include <QPixmap>
#include <QDebug>
#include <QMouseEvent>

namespace{
    int aa = 0;
}

MyWidget::MyWidget(QWidget *parent)
    : QWidget{parent}
{
    resize(400,600);
    QPixmap pixmap;
    pixmap.load(":/image/125.png");
    top_show_area_ = new QLabel("cursor",this);
    top_show_area_->move(0,0);
    top_show_area_->setFixedHeight(20);
    image_show_area_= new QLabel(this);
    image_show_area_->move(0,20);
    image_show_area_->setPixmap(pixmap);
    image_show_area_->setMouseTracking(true);//移动触发,不再需要鼠标点击
    image_show_area_->installEventFilter(this);//为QLabel部件在本窗口上安装事件过滤器
}

//事件过滤器
bool MyWidget::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == image_show_area_){//判断部件
        if(event->type() == QEvent::MouseMove){//判断事件
            //可以强制转换为鼠标事件使用
            qDebug() << aa++ << static_cast<QMouseEvent*>(event)->globalPos();
            return true;//该事件已经被处理
        }else{
            return false;//如果是其他事件,可以进一步的处理
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值