Qt中EventFilter过滤鼠标事件

在qt界面中,响应事件的往往是界面,而界面上的控件则被屏蔽,比如想要让QLabel响应鼠标事件,之前已写到可以通过把QLabel提升为类,在类中自定义鼠标响应事件及重绘事件等事件。最近学习发现通过EventFilter过滤事件更方便且高效。
在界面类的头文件添加

public slots:
    bool eventFilter(QObject *, QEvent *);

在源文件中为需要响应事件的控件安装事件过滤

ui->picLabel->installEventFilter(this); ui->picLabel->setMouseTracking(true);

然后在事件监视函数eventFilter()中监视响应事件

bool Dialog::eventFilter(QObject *watched, QEvent *event)

整体代码如下

dialog.h
#ifndef DIALOG_H
#define DIALOG_H

#include 
#include 
namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
public slots:
    bool eventFilter(QObject *, QEvent *);
private:
    Ui::Dialog *ui;
};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    ui->picLabel->installEventFilter(this);
    ui->picLabel->setMouseTracking(true);
}

Dialog::~Dialog()
{
    delete ui;
}
bool Dialog::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->picLabel)
    {
        if(event->type()==QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = (QMouseEvent *)event;
            if(mouseEvent->buttons()&Qt::LeftButton)
            {
                QPoint p=mouseEvent->pos();
                QString s="x= "+QString::number(p.x())+" y= "+QString::number(p.y());
                ui->posLineEdit->setText(s);
            }
        }
        if(event->type()==QEvent::MouseMove)
        {
            QMouseEvent *mouseEvent = (QMouseEvent *)event;

            QPoint p=mouseEvent->pos();
            QString s="x= "+QString::number(p.x())+" y= "+QString::number(p.y());
            ui->movePosLineEdit->setText(s);

        }
    }
    return QDialog::eventFilter(watched,event);
}

Qt中EventFilter过滤鼠标事件_第1张图片

你可能感兴趣的:(qt)