1

I'm developing a plugin for creating points and lines, but I noticed that when using QgsMapToolEmitPoint the cursor doesn't have snapping functionality

canvas = iface.mapCanvas()
addPoint = QgsMapToolEmitPoint(canvas)
canvas.setMapTool(addPoint)

I noticed that the created tool does not have snapping functionality. Is it possible to create a MapTool with QgsMapToolEmitPoint that has snapping functionality?

enter image description here

1 Answer 1

4

You need to sub-class QgsMapToolEmitPoint instead of using the default implementation. Here is a basic example:

class CustomMapTool(QgsMapToolEmitPoint):

    def __init__(self, canvas):
        self.canvas = canvas
        super(CustomMapTool, self).__init__(self.canvas)
        self.layer = iface.activeLayer()
        self.snap_indicator = QgsSnapIndicator(self.canvas)
        self.snap_utils = self.canvas.snappingUtils()

    def canvasMoveEvent(self, e):
        snap_match = self.snap_utils.snapToMap(e.pos())
        self.snap_indicator.setMatch(snap_match)

    def canvasPressEvent(self, e):
        point = e.mapPoint()
        if self.snap_indicator.match().type():
            snapped_point = self.snap_indicator.match().point()


canvas = iface.mapCanvas()
map_tool = CustomMapTool(canvas)
canvas.setMapTool(map_tool)

enter image description here

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.