I want to get x/y coordinates of a point on mouse click for a point and need to use those coordinates to evaluate other values as per other modules already define.
How can I get x/y coordinates on mouse click in QGIS and print those in PyQGIS?
asked Aug 30, 2017 at 0:01
-
You need QgsMapToolEmitPoint class to do that (please, see my answer).xunilk– xunilk2017年08月30日 01:05:11 +00:00Commented Aug 30, 2017 at 1:05
1 Answer 1
You need QgsMapToolEmitPoint class to do that. Following code works well for that purpose:
from qgis.gui import QgsMapToolEmitPoint
def display_point( pointTool ):
print '({:.4f}, {:.4f})'.format(pointTool[0], pointTool[1])
# a reference to our map canvas
canvas = iface.mapCanvas()
# this QGIS tool emits as QgsPoint after each click on the map canvas
pointTool = QgsMapToolEmitPoint(canvas)
pointTool.canvasClicked.connect( display_point )
canvas.setMapTool( pointTool )
However, if you prefer a class, following code can also be used:
from qgis.gui import QgsMapToolEmitPoint
class PrintClickedPoint(QgsMapToolEmitPoint):
def __init__(self, canvas):
self.canvas = canvas
QgsMapToolEmitPoint.__init__(self, self.canvas)
def canvasPressEvent( self, e ):
point = self.toMapCoordinates(self.canvas.mouseLastXY())
print '({:.4f}, {:.4f})'.format(point[0], point[1])
canvas_clicked = PrintClickedPoint( iface.mapCanvas() )
iface.mapCanvas().setMapTool( canvas_clicked )
answered Aug 30, 2017 at 1:03
-
1This worked, thank you. May be you could add how to unset the listener:
unsetMapTool(canvas_clicked)
Rodrigo E. Principe– Rodrigo E. Principe2019年07月29日 14:11:06 +00:00Commented Jul 29, 2019 at 14:11 -
When you try to use your own maptool in this case, it does not output anything to the console - is there are a reason for that? So lets say you set
canvas.setMapTool( pointTool )
- it outputs noting to the console, yet the crosshair shows on the mapcanvas. Thanks @xunilkuser1655130– user16551302020年11月17日 19:22:33 +00:00Commented Nov 17, 2020 at 19:22 -
I'm adding these lines to a function inside a plugin, and nothing happens... not even the crosshair. Error log is "NoneType: None" (I can keep working with the plugin, just the focus shifts from the plugin dialog to QGIS, that's all)...S.E.– S.E.2022年04月21日 16:07:20 +00:00Commented Apr 21, 2022 at 16:07
lang-py