简体   繁体   中英

Qt MouseMove event not being caught in eventFilter()

It is simply not working. I have enabled mousetracking, then installed the event filter, everything is fine, except for MouseMove events. Any assistance, please?

#include "mainwindow.h"
#include "ui_mainwindow.h"

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

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
    if(event->type() == QEvent::MouseMove)
    {
        QMouseEvent *mEvent = (QMouseEvent*)event;
        qDebug() << mEvent->pos();
    }
    return false;
}

This line is quite strange, you ask this to filter himself

installEventFilter(this);

I would'nt be surprised if Qt did simply ignore self-filtering events

Try this for detecting mouse move events in the central widget:

centralWidget()->installEventFilter(this);
centralWidget()->setMouseTracking(true);

Or, for detecting mouse move events in the MainWidget, use setMouseTracking(true) on this and instead of adding an event filter, reimplement the mouseMoveEvent() protected function:

//In constructor:
setMouseTracking(true);

and

void MainWindow::mouseMoveEvent(QMouseEvent * event)
{
    //do stuff here

    event->reject(); //To avoid messing QMainWindow mouse behavior
}

this is another design issue of QT: eventFilter will not receive the event... UNLESS you override mouseMoveEvent and ignore the signal there.

void mouseMoveEvent(QMouseEvent* e) override { e->ignore(); }

Now, eventFilter can be used... and this is often desirable because you might have some eventFilter class that you would like to use with multiple widgets.

QMainWindow has centralWidget that is located over MainWindow area. Try to add to MainWindow constructor this code

ui->centralWidget->setMouseTracking(true);

Mouse events will come first to MainWindow and then to centralWidget.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM