Tracking mouse move in QGraphicsScene class

cuteCAT picture cuteCAT · Oct 14, 2011 · Viewed 22.4k times · Source

I subclassed QGraphicsScene and added method mouseMoveEvent to handle mouse move event. I created a ruler on top of GraphicsView and have the ruler tracking mouse movement. In the QGraphicsScene::mousemoveEvent I calls mouseMoveEvent of the ruler widget explcitely. The purpose is to have the ruler knows that the current mouse position.

Now it seems that QGraphicsScene::mousemoveEvent is not called when I move the mouse. However, I can get it to work if I press the left mouse button and move it while holding the button. This is not what I'd like to see; I'd like this method is called whenever I place the mouse over the view and move the mouse.

Is there any workaround?

Answer

Mat picture Mat · May 28, 2012

As stated in the QGraphicsView documentation, the view is responsible for translating mouse and keyboard events into scene events and propagating that to the scene:

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.

Since mouse move events only occur when a button is pressed by default, you need to setMouseTracking(true) on the view for the move events to generated in the first place, so that it can forward those to the scene.
Alternatively, if you don't need the translation to scene coordinates, you could reimplement the mouseMoveEvent in the view directly rather than in your scene. But in this case, make sure you call the base class QGraphicsView::mouseMoveEvent in your implementation, so that hover events are properly generated for the items in your scene.