PyQGIS – Running Function from Double Click with PyQGIS

pyqgispyqt

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…

Best Answer

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) 
Related Question