3

I'm trying to add labelling to a polygons vector layer called "myVectorLayer" with the following code:

palyr = QgsPalLayerSettings()
palyr.readFromLayer(myVectorLayer)

palyr.enabled = True
palyr.fieldName = 'name'
palyr.placement= QgsPalLayerSettings.OverPoint
palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'8','')

palyr.writeToLayer(myVectorLayer) 

It does not give me any error but the labelling does not appear. Any idea how to fix this?

рüффп
  • 204
  • 1
  • 5
  • 18
Nora 27
  • 81
  • 5

1 Answers1

2

See How to obtain rotation field name defined in the Labels "Data Defined" section in pyqgis?. You will need to refresh the map canvas at the end of your code to see changes.

You are setting the palyr.fieldName to 'name,' which will need to be a valid attribute table field. Please verify.

You mention adding the labeling settings to "myVectorLayer." The QgsPalLayerSettings().readFromLayer(vlayer) function needs a QgsVectorLayer for its parameter. It is unclear whether your "myVectorLayer" (in your code) is a QgsVectorLayer instance, or just the textual name of the layer. If it is the latter, you will need to query QgsMapLayerRegistry to find its QgsMapLayer instance:

QList<QgsMapLayer *> QgsMapLayerRegistry::mapLayersByName(QString layerName)    
dakcarto
  • 7,754
  • 26
  • 34