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):
        print(pointTool.x(), pointTool.y())
    except AttributeError:

# 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)

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):
            print(pt.x(), pt.y(), bt)
        except AttributeError:
            print("No attribute")

    def on_create_ignition_point(self):
        canvas = self.iface.mapCanvas()
        pointTool = QgsMapToolEmitPoint(canvas)

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
    In a plugin, should create instance attributes for canvas: 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 the initGui method: self.pointTool.canvasClicked.connect(self.display_point). Finally, in your on_create_ignition_point() method, just set the canvas map tool: self.canvas.setMapTool(self.pointTool).
    – Ben W
    Commented Feb 28, 2022 at 23:35
  • 1
    I answered a similar question here: gis.stackexchange.com/questions/403628/… Maybe you will find it useful.
    – Ben W
    Commented Feb 28, 2022 at 23:35
  • 1
    Thank you for your answers, moving the variables to instance attributes solved the problem. Of course letting the point tool be a local variable was not a good idea. Commented Mar 4, 2022 at 12:59
  • 2
    Perhaps you could create an answer with your working code and explanation of the changes you made. It will help future readers of this question.
    – Matt
    Commented Mar 4, 2022 at 13:01

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):
            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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.