5

I am using Python for QGIS 2.0.1 and I have a vector layer of points representing the positions of state labels. I want to display the 'state abbreviation' attribute on the corresponding point for each feature.

Does anyone have an example using QgsPalLabeling to do this?

This is a fairly simple process using the new Labeling tab of the GUI, but I have not found any documentation to make this work programmatically using PyQGIS.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
will1906
  • 121
  • 1
  • 6

1 Answers1

7

Just figured this one out thanks to a modification of an older post by dakcarto.

Basically the python would need to look like this (replace everything in bold):

palyr = QgsPalLayerSettings()
palyr.readFromLayer(My Vector Layer)
palyr.enabled = True
palyr.fieldName = 'My Attribute Field Name'
palyr.placement= QgsPalLayerSettings.OverPoint
palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'8','')
palyr.writeToLayer(My Vector Layer)
will1906
  • 121
  • 1
  • 6
  • For QGIS 3.x, have a look at here:https://gis.stackexchange.com/questions/273266/reading-and-setting-label-settings-in-pyqgis-3/273268#273268 – juminet Nov 29 '21 at 16:27