PDA

View Full Version : MouseMoveEvent not called when cursor over child widget



nilot
10th April 2017, 09:52
Hello,
In a QDialog, I would like to display the mouse coordinates when the mouse is above a widget which is included in the QDialog.
Using "setMouseTracking", it works when the widget is a QLabel but it doesn't when it is a QGraphicsView : if the mouse moved above the qgraphicsview, the function mouseMoveEvent of the QDialog isn't called. Why ?

Example:

#include <QDialog>
#include <QGridLayout>
#include <QDebug>
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QLabel>

class MyDialog : public QDialog
{
public:
MyDialog() : QDialog()
{setMouseTracking(true);}
protected:
void mouseMoveEvent(QMouseEvent *event)
{
qDebug()<<QCursor::pos();
}
};

int main(int argc, char **argv){
QApplication app(argc, argv);
MyDialog dlg;
QGridLayout *l = new QGridLayout(&dlg);
QLabel* label1 = new QLabel("Above Label");
label1->setMouseTracking(true);
QGraphicsScene* scene = new QGraphicsScene(0, 0, 100, 100);
QGraphicsView* view = new QGraphicsView(scene);
view->setMouseTracking(true);
l->addWidget(label1,0, 0);
l->addWidget(view, 0, 1, 2, 1);
return dlg.exec();
}

Thank you.

high_flyer
10th April 2017, 11:21
This part of the QGraphicsView docs seems interesting:

You can interact with the items on the scene by using the mouse and keyboard. QGraphicsView translates the mouse and key events into scene events, (events that inherit QGraphicsSceneEvent,), and forward them to the visualized scene. In the end, it's the individual item that handles the events and reacts to them. For example, if you click on a selectable item, the item will typically let the scene know that it has been selected, and it will also redraw itself to display a selection rectangle. Similiary, if you click and drag the mouse to move a movable item, it's the item that handles the mouse moves and moves itself. Item interaction is enabled by default, and you can toggle it by calling setInteractive().
As a test you can try to call setInteractive(false) and see if this changes things.
Depending on your need to interact with your view you might need to reimplent the mouse event handlers to forward the events to your dialog.

There is another approach as well:
you can install an event filter on your view:
See http://doc.qt.io/qt-5/qobject.html#installEventFilter for more details on that.

A third option is to try to use grabMouse():
http://doc.qt.io/qt-5/qwidget.html#grabMouse