user2683843 user2683843 - 3 months ago 50
C++ Question

Qt mouse events not working in QGraphicsScene

I am using Qt 5.7 (the latest version). I can't get the mouse events to work in QGraphicsScene, but they work in window outside of my scene. I have followed this question.

So I have overwritten

QWidget::mouseMoveEvent()
in my main widget's subclass like this:

// header:
class MyWidget {
...
void mouseMoveEvent( QMouseEvent * event );
};

// source:
MyWidget::MyWidget() {
setMouseTracking();
}

void MyWidget::mouseMoveEvent( QMouseEvent * event ) {

}


It doesn't work for:
mouseMoveEvent
,
mouseGrabber
,
mousePressEvent
,
mouseReleaseEvent
, or
mouseDoubleClickEvent
. But somehow it only works for
mousePressEvent
.

Could this be a bug in Qt?

SOURCE CODE:
In objectloader.cpp

ObjectLoader::ObjectLoader(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ObjectLoader)
{
ui->setupUi(this);
scene=new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
ui->graphicsView->setMouseTracking(true);
setMouseTracking(true);



}


Thats were i set mouse tracking twice
In objectloader.h
Then i define that method in objectloader.h

class ObjectLoader : public QMainWindow
{
Q_OBJECT


public:
explicit ObjectLoader(QWidget *parent = 0);
~ObjectLoader();

private slots:
void mouseMoveEvent(QMouseEvent *event);
protected:

private:

};

#endif // OBJECTLOADER_H


And implementation of that method in objectloader.cpp

void ObjectLoader::mouseMoveEvent(QMouseEvent *event){

qDebug()<<"Mouse moved";

}

Answer

When a mouse event is generated by Qt it is generally passed initially to the QWidget that was under the mouse pointer when the event was generated. If that QWidget accepts the event then no further processing will take place. If the event isn't accepted then Qt may propogate the event to that QWidget's parent and so on.

In your particular case the mouse move events you are interested in are being sent to the QGraphicsView/QGraphicsScene conponents where they are being accepted and, hence, no further processing takes place. In a case like that you generally need to install an event filter to intercept and process the events of interest.