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"
        print"Right button pressed"

I am trying to call this function as follows:


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

  • What do u call "unable to call the function" ? U should u show us the full code u're using ... – snaileater Jun 18 '15 at 7:57

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

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

    def deactivate(self):
        # Revert the button text
        """ QgsMapToolIdentify.deactivate() """

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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