4

My goal is to define labels programmatically for the case similar for the figure below:

labelling layer manually using QGIS UI

But I didn't find any guidance how to do so using Python.

I have a feeling it could be done using QgsLabel but didn't find any working exmaple how to do so.

I seek some example how to do so;

If I'm wrong with QgsLabel idea, can you explain briefly the right approach for this?

As usual some code example could be very useful.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Egor.Baykov
  • 291
  • 4
  • 11

1 Answers1

5

Activate your layer in the ToC and try this in the QGIS Python console:

layer = iface.activeLayer()
layer.setCustomProperty("labeling", "pal")
layer.setCustomProperty("labeling/enabled", "true")
layer.setCustomProperty("labeling/fontFamily", "Arial")
layer.setCustomProperty("labeling/fontSize", "10")
layer.setCustomProperty("labeling/fieldName", "ename")
layer.setCustomProperty("labeling/placement", "2")
iface.mapCanvas().refresh()

An alternate way would be to use QgsPalLayerSettings(), like in MultiLine field-name label referencing, however, it didn't work for me in QGIS v.2.8.

By the way, next time try this kind of search.

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178