7

Goal: The snapping functionality should be enabled and disabled.

I use the function setSnapSettingsForLayer. Convenience function to set snap settings per layer. Short Example:

QgsProject.instance().setSnapSettingsForLayer(layer.id(), True, 2, 1, 10, True)

This approach has already been explained in another post: How to enable the snapping for a layer with the tolerance value with python programming

Up to this point everything works. Now we come to the problem. How can I disable the snapping functionality?

If I set the second parameter in the function setSnapSettingsForLayer to False (to enable the layer snapping), then nothing happens. The Snapping remains activated. Even if I change an another parameter e.g. tolerance, also does not change.

So, how can the Snapping be enabled and disabled while editing?

UPDATE:

Despite my answer, the problem is not yet solved. By choosing Settings -> Snapping options you will find the following window

enter image description here

Only when I confirm this window with the 'OK' button, the code in my answer works. Only now the Snapping can be turned off and on during processing. Has anyone any idea?

3

2 Answers 2

4

I seem to have found the problem. In QGIS all layers were initially activated for the Snapping. First I disable any snapping operations. Subsequently, the Snapping is enabled for a few layers.

for item in QgsMapLayerRegistry.instance().mapLayers().values():
    QgsProject.instance().setSnapSettingsForLayer(item.id(), False, 2, 0, 2, True)
    fieldLayer = mapUtils.getLayerByName(agroInstance.dictData['lpisid'])
    backgroundLpisLayer = mapUtils.getLayerByName('LPISe')
    if checked:
        # Convenience function to set snap settings per layer.
        # it defines the snapping options:
        # id : the id of your layer, True : to enable the layer snapping, 2 : options (2: vertex+segment), 0: type of unit on map, 2 : tolerance, true : avoidIntersection)
        QgsProject.instance().setSnapSettingsForLayer(layerA.id(), True, 2, 0, 2, True)
        QgsProject.instance().setSnapSettingsForLayer(layerB.id(), True, 2, 0, 2, True)

The variable 'checked' checks whether a toggle button has been pressed. With this unsightly way I can turn the snapping on and off.

2

works in QGIS 3, to toggle snapping on/off use

iface.mapCanvas().snappingUtils().toggleEnabled()

https://qgis.org/api/classQgsSnappingUtils.html

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.