6

How can a double-click in the QGIS canvas be used to run a function in PyQGIS?

For example, I want to access the name of each feature I'm selecting with a double-click.

Code sample to access the selected features names (their names are stored in the first field of their attribute table):

from qgis.core import *

def get_feature_name(self):
    vlayer = QgsProject.instance().mapLayersByName('layer')[0]

    for f in vlayer.selectedFeatures():
        feature_name = f.attribute(0) # results in Group 1
        print(feature_name)

I'm aware there is the canvasDoubleClickEvent() but I'm struggling to make it work...

1 Answer 1

5

I'll just add my recent answer from this question to this post. See the linked answer for a brief explanation, I just changed the event type to filter for double clicks.

class MouseClickFilter(QObject):

    def __init__(self, parent=None):
        super(MouseClickFilter, self).__init__(parent)
    
    def eventFilter(self, obj, event):
        if event.type() == QEvent.MouseButtonDblClick:
            print('double clicked')
            # add the function you want to run after double clicked here
            
        return False


click_filter = MouseClickFilter()
iface.mapCanvas().viewport().installEventFilter(click_filter)

EDIT:
Below is an example using the QgsMapTool approach, which was originally linked in the question. Might even be an easier solution, but won't be suitable if you want to run the double click function regardless of the selected map tool.

def canvasPressEvent(event):
    print('double clicked')

tool = QgsMapTool(iface.mapCanvas())
tool.canvasDoubleClickEvent = canvasPressEvent
iface.mapCanvas().setMapTool(tool) 
2
  • Ok so instead of using canvasDoubleClickEvent() you used the QMouseEvent MouseButtonDblClick ? Thanks for the quick reply !
    – wanderzen
    Commented May 3, 2022 at 13:01
  • 1
    @wanderzen Well basically yes, but these are just two different approaches. It depends on use case which method you want to use. So consider whether you want to use a map tool (which doesn't have to be active all the time) or need the function to run regardless of the selected map tool (e.g. having another map tool active). I'll update my answer!
    – CodeBard
    Commented May 3, 2022 at 13:22

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.