[GIS] How to get labels to show from a python plugin in QGIS

labelingpyqgisqgisqgis-pluginsvector-layer

I have created a memory polygon vector layer from my plugin in QGIS and it looks fine:

my_layer = QgsVectorLayer('Polygon', 'My layer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(my_layer, False)

# I want to place the layer at a specified position in the layer tree.
root_node = QgsProject.instance().layerTreeRoot()
root_node.insertLayer(3, my_layer)

Then I applied some styling from the plugin and it works too. Finally I wanted to enable some labelling from within the plugin:

label = QgsPalLayerSettings()
label.readFromLayer(my_layer)
label.enabled = True
label.fieldName = '$area'
label.writeToLayer(my_layer)

The problem is that the labels are not showing. I need to manually change just one simple thing in the label settings for the specified layer afterwards and then they show with my customised settings.

I see that others are using the setCustomProperty on the layer instead:

my_layer.setCustomProperty('labeling', 'pal')
my_layer.setCustomProperty('labeling/enabled', 'true')
my_layer.setCustomProperty('labeling/fieldName', '$area')

But that doesn't work either, I still need to manually change something to get them to show.

I have tried both

my_layer.triggerRepaint()
iface.mapCanvas().refresh()

It doesn't seem to have any effect though.

It doesn't seem to have any effect either if I apply the labeling before or after I add the layer to the QgsMapLayerRegistry.

Is this a known problem, or can you see what it is that I am missing here?

Best Answer

You need this:

my_layer.setCustomProperty("labeling/drawLabels",  "True")

, or

label.drawLabels = True

You choose.