Thursday 11 April 2019

pyqgis - Capturing mouse movement on QgsMapCanvas?


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?



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...