Installing an event filter and implenmenting mouseMoveEvent does not enable tracking cursor position

271 views Asked by At

I am trying to implement in my program, that if the mouse hovers over my QChartView widget, I get back the coordinates of the cursor.

I already tried, by installing an event filter on the widget:

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

and then writing the method for a mouse event:

void MainWindow::mouseMoveEvent(QMouseEvent* event) {
    qDebug() << event->pos();
}

But, I only get the output when I click on the Mainwindow and hold the mouse button, which I clicked. When I click on the widget chartView, I don't get any output.

I need to get output, when the mouse is hovering over chartview.

2

There are 2 answers

0
A.R.M On

Installing an event filter means you want to customize event handling inside QObject::eventFilter, so reimplementing mouseMoveEvent goes against the point of using an event filter.

So you do not get output because you have not reimplemented the eventFilter, and mouseMoveEvent does not get triggered unless you do setMouseTracking(true);.

Supposing that this is MainWindow, here is an example reimplementation of eventfilter:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type == QEvent::MouseMove)
    {
        qDebug() << event->pos();
    }
}

Note: if you install your mainWindow as an event filter for multiple objects, you need to check the object as well before customizing the event handling, to avoid undesired behavior.

Example:

if(event->type == QEvent::MouseMove && obj->objectName() == "yourObjectName")

Or

if(event->type == QEvent::MouseMove && qobject_cast<QChartView*>(obj) == ui->chartView)
0
SebDieBln On

You don't need an event filter. You need to reimplement the methods QWidget::enterEvent() and QWidget::leaveEvent().

enterEvent() is called when the mouse enters the widget and leaveEvent() when it leaves it again.