[GIS] Identifying Left and Right Mouse Button Clicks in PyQgis application

pyqgispyqtpythonqgis-plugins

I am relatively new to PyQt. I am trying create a custom plugin for Qgis which enables the user to select some features by drawing polygon on the canvas using mouse clicks and then performs intersection of the selected features with another layer. What I want to do is that when user right clicks on the canvas the polygon selection should stop. For this I have to identify between the right and left mouse signals. I have made a dummy function just to test this functionality:

def mousePressEvent(self):
    print "code enters mousePressEvent function"
    if event.buttons() == "Qt::LeftButton"
        print"Left button pressed"
    else:
        print"Right button pressed"

I am trying to call this function as follows:

QObject.connect(self.clickTool,SIGNAL("canvasClicked(QMouseEvent,Qt::MouseButton)"),self.mousePressEvent)

But I am unable to call the function. I guess I am doing something wrong in canvasClicked section.

Best Answer

I think you are best trying to subclass an existing tool. Here is an example with the identify tool.

class MySelectorTool(QgsMapToolIdentify):
    """Inherits the QGIS identify tool (tool is deactivated once another tool takes focus)"""
    def __init__(self, toolbar):
        QgsMapToolIdentify.__init__(self, canvas)

    def activate(self):
        # Deal with changing the button text + change cursor
        self.toolbar.street_sel_btn.setText("ON")
        self.canvas.setCursor(self.cursor)

    def canvasReleaseEvent(self, mouseEvent):
        # Here you can deal with the mouse click events
        results = self.identify(mouseEvent.x(), mouseEvent.y(), [self.something_interesting])
        self.your_logic_here()results)

    def deactivate(self):
        # Revert the button text
        """ QgsMapToolIdentify.deactivate() """
        self.toolbar.street_sel_btn.setText("OFF")

    def your_logic_here(self, reaults):
       # Print to console
       print results[0], results[1]

And to active are the tool:

def connect_selector_tool(self):
    # Set the map tool (**MySelectorTool instance**)
    self.iface.mapCanvas().setMapTool(**MySelectorTool instance**)