1

I try to toggle labels on/off for a layer in QGIS 2.18 with PyQGIS. In PyQGIS 3 a method QgsVectorLayer().setLabelsEnabled() seem to have been added, but as far as I see, such is not available in PyQGIS 2 (There is no such hint Since QGIS 3.0 as well in the doku for PyQGIS 3 https://qgis.org/api/classQgsVectorLayer.html#a4cdece41437b32f4adafeb1caa10ad1b).

My first try was to access the labeling configuration of the layer with sth. like

label_settings = my_layer.labeling().settings()
label_settings.enabled = not label_settings.enabled
my_layer.setLabeling(label_settings)

but the labeling() and setLabeling() methods are not available in the python bindings (e.g. https://qgis.org/api/2.18/classQgsVectorLayer.html#ada12f21c42e2f3c2eaa2b234ff25ed28).

There is a method QgsVectorLayer().enableLabels() as well, but this is deprecated (https://qgis.org/api/2.18/classQgsVectorLayer.html#ae7735460da1518febff85575851b8e88) and seems to have no effect.

Any suggestions?

1

Try using:

layer.setCustomProperty("labeling/enabled", True) # On
layer.setCustomProperty("labeling/enabled", False) # Off
  • 1
    I just noticed, that this approach has no effect for layers with rule based labels, just for 'normal' labels. I noticed in addition that disabling labeling via gui/dialogue for a layer with rule based labels causes the existing rules to be deleted. I think that keeping them for later re-enabling rule based labeling would be worth another question... – Jochen Schwarze Dec 12 '18 at 12:16
  • @JochenSchwarze - You are correct in that this does not affect rule-based labels as mentioned in the comments of this post. I also asked a question regarding using PyQGIS specifically for rule-based labels and this was introduced for QGIS 3. Hope this helps :) – Joseph Dec 12 '18 at 12:27
  • 1
    Greatly! Can not wait for QGIS 3.4 to become LTR... – Jochen Schwarze Dec 12 '18 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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