PyQGIS – Capturing Mouse Movement on QgsMapCanvas Using PyQt Libraries

pyqgispyqt

I have a python app that uses QgsMapCanvas as map display. I put it inside a QWidget, which is then inside another control. The problem is that there seems to be no way of tracking mouse move event on the QgsMapCanvas itself. I've tried connect as below:

QtCore.QObject.connect(self.canvas, QtCore.SIGNAL("mouseMoveEvent()"), self.canvasMoveEvent)

it doesn't trigger that event when the mouse is moving inside the canvas area.

How do I trap mouse movement inside a QgsMapCanvas in the above setup?

Best Answer

QgsMapTool

You probably want to implement a QgsMapTool and set this as the active map tool.

This offers several methods which you can implement to react

  • canvasMoveEvent
  • canvasPressEvent
  • canvasReleaseEvent
  • canvasDoubleClickEvent
  • and some more

You will then have to do

canvas.setMapTool( yourmaptool )

to make it active.

xyCoordinates event

If you really need to get the information from outside a map tool, you can connect to the xyCoordinates event

canvas.xyCoordinates.connect( self.canvasMoveEvent )

eventFilter

Or install an eventFilter on the map canvas. This is a very mighty Qt approach, it's the (non-elegant) sledgehammer to do things but it's the way to go if you need to even modify the mouse events before they are further processed by other tools.

Related Question