1

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;
}
ImQ009
  • 325
  • 4
  • 12

3 Answers3

4

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
}
galinette
  • 8,896
  • 2
  • 36
  • 87
4

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.

IceFire
  • 4,016
  • 2
  • 31
  • 51
1

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.