I'm trying to grab the coordinates from a click. If I type this code (obtained from Getting coordinates from mouse click in QGIS 3 (python plugin)):
def display_point(pointTool):
try:
print(pointTool.x(), pointTool.y())
except AttributeError:
pass
# 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)
display_point(pointTool)
in the python console it works perfectly. But if I place it inside my plugin class it does not work, don't even get the cross mouse pointer and I have no idea why is not working:
...
def display_point(self, pt, bt):
try:
print(pt.x(), pt.y(), bt)
except AttributeError:
print("No attribute")
def on_create_ignition_point(self):
print("IN")
canvas = self.iface.mapCanvas()
pointTool = QgsMapToolEmitPoint(canvas)
pointTool.canvasClicked.connect(self.display_point)
canvas.setMapTool(pointTool)
print('OUT')
...
the function on_create_ignition_point
gets called from a toolbar button and the IN and OUT messages are printed. Also created a class like is explained in Getting coordinates of point on mouse click using PyQGIS with the same results.
Any hints on what I'm doing wrong?
1 Answer 1
Following the comments provided did the trick. Moving the local variables to instance attributes solved the problem.
The final code is this:
if not (self._pointTool is None):
self._pointTool.canvasClicked.disconnect()
del self._pointTool
self._previousTool = None
self._pointTool = None
# Store the previous tool in use b the user
canvas = self._iface.mapCanvas()
self._previousTool = canvas.mapTool()
# Set the tool and onClick callback
self._pointTool = QgsMapToolEmitPoint(canvas)
self._pointTool.canvasClicked.connect(self.on_point_callback)
canvas.setMapTool(self._pointTool)
self.canvas = self.iface.mapCanvas()
and pointTool:self.pointTool = QgsMapToolEmitPoint(self.canvas)
in the__init__
method of the main plugin class. Then create the signal/slot connection in theinitGui
method:self.pointTool.canvasClicked.connect(self.display_point)
. Finally, in youron_create_ignition_point()
method, just set the canvas map tool:self.canvas.setMapTool(self.pointTool)
.