2

I have a code that reacts to a mouse click. I click on the label of an object and get the ID of this object. Everything works perfectly. But I need to do all the same when some other tool is active ("Move a Label..." tool). Or at worst, so that this code is always executed regardless of the selected tool. Is there a way to achieve this?

def canvasPressEvent(event):
    x = event.pos().x()
    y = event.pos().y()
    point = canvas.getCoordinateTransform().toMapCoordinates(x, y)
    labels = iface.mapCanvas().labelingResults().labelsAtPosition(QgsPointXY(point))    
    if labels:
        print (labels[0].featureId)
from qgis.gui import QgsMapToolEmitPoint
canvas = iface.mapCanvas()
pointTool = QgsMapToolEmitPoint(canvas)
pointTool.canvasPressEvent = canvasPressEvent
canvas.setMapTool(pointTool) 

1 Answer 1

2

One way to get the coordinates regardless of the selected tool is using an Event Filter to intercept the mouse events of the QgsMapCanvas object.

Within the event filter function there is a check for the correct event type, in this case QEvent.MouseButtonPress, and then you can access coordinates exactly the same as in your code example.


class MouseClickFilter(QObject):

    def __init__(self, parent=None):
        super(MouseClickFilter, self).__init__(parent)
    
    def eventFilter(self, obj, event):
        if event.type() == QEvent.MouseButtonPress: 
            x = event.pos().x()
            y = event.pos().y()
            point = iface.mapCanvas().getCoordinateTransform().toMapCoordinates(x, y)
            print(point)
            
        return False
            

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

Note that if you want to filter mouse events, you need to install the event filter on the canvas' viewport. For other events (e.g. key press) iface.mapCanvas().installEventFilter(filter) is sufficient.

1
  • 1
    Wow! This is magic, works great! Thanks a lot! Apr 28, 2022 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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