1

I working with QGIS 3.20. I want to write a PyQGIS script to automate switching the field used for labeling in numerous layers. Currently the layers are labeled from values of a field that is different for each layer.

I thought I will follow this procedure:

  1. Get the field name that is currently used for labeling (say field "X") in a variable
  2. Add a new field "Label" and populate its values according to the values in field "X"
  3. Set the labeling field to the "Label" field

I know how to do number 2 and I am looking for a way to do number 1 and 3. So my questions are: how do I get the labeling field name (to store in a variable)? How do I change the labeling field?

In the UI this is the labeling field I want to access and change (however its name is different for each layer):

Labeling field

What would be the way to go?

1 Answer 1

0

My answer is based on two answers :

Getting label feature with PyQGIS? from Leo Cardona for step 1

QgsPalLayerSettings error from ndawson for step 3

This is the code used for step 1 and step 3 :

layer = iface.activeLayer()    
# STEP 1
labeling = layer.labeling()
palyr = labeling.settings()
currently_used_field_name = palyr.fieldName
print (currently_used_field_name)
# this will print : X

#STEP 3
new_label_field = "Label"
label_settings = QgsPalLayerSettings()
label_settings.drawLabels = True
label_settings.fieldName = new_label_field
layer.setLabeling(QgsVectorLayerSimpleLabeling(label_settings))
layer.triggerRepaint()
2
  • Thank you very much! That was exactly what I needed! Could you also tell me how to distinguish if a layer has single labelling (based on the values of a field) or rule based labeling?
    – mikmar
    Jul 13, 2021 at 13:56
  • @mikmar you can use palyr.getLabelExpression().isField() wich is going to return a boolean, TRUE if your label is based only on a field and FALSE if your label is based on an expression. See the doc of QgsExpression. qgis.org/pyqgis/master/core/…
    – JULESG
    Jul 13, 2021 at 16:17

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.