PyQGIS – Programmatically Check for Mouse Click in PyQGIS

pyqgisqgis-plugins

I want to know how to check for a mouse click in QGIS. I am trying to write a python plugin and want to provide functionality similar to the "Select Single Feature" tool that already exists in QGIS.

I checked the QGIS api docs and found

QgsMapCanvas::CanvasProperties::mouseButtonDown

This sounds promising. I have a QgsMapCanvas object but I can't see how to access the mouseButtonDown attribute.

I am completely new to the QGIS API.

Best Answer

The best way to make a new tool like the Select Single Feature tool is to inherit from the QgsMapTool class. When your tool is active, which can be set using QgsMapCanvas::setMapTool, any keyboard or click events the canvas gets will be passed onto your custom tool.

Here is a basic QgsMapTool class

class PointTool(QgsMapTool):   
    def __init__(self, canvas):
        QgsMapTool.__init__(self, canvas)
        self.canvas = canvas    

    def canvasPressEvent(self, event):
        pass

    def canvasMoveEvent(self, event):
        x = event.pos().x()
        y = event.pos().y()

        point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)

    def canvasReleaseEvent(self, event):
        #Get the click
        x = event.pos().x()
        y = event.pos().y()

        point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)

    def activate(self):
        pass

    def deactivate(self):
        pass

    def isZoomTool(self):
        return False

    def isTransient(self):
        return False

    def isEditTool(self):
        return True

You can do what you need in canvasReleaseEvent, etc

To set this tool active you just do:

tool = PointTool(qgis.iface.mapCanvas())
qgis.iface.mapCanvas().setMapTool(tool)