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...

wanderzen
  • 2,130
  • 6
  • 26

1 Answers1

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)

CodeBard
  • 3,511
  • 1
  • 7
  • 20
  • Ok so instead of using canvasDoubleClickEvent() you used the QMouseEvent MouseButtonDblClick ? Thanks for the quick reply ! – wanderzen May 03 '22 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 May 03 '22 at 13:22