#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;//如果是其他事件,可以进一步的处理
}
}
}