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.enabled = True
label.fieldName = '$area'

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


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?


You need this:

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

, or

label.drawLabels = True

You choose.


You want to show expression based label, so you have to set:

label.isExpression = True

and for visible labels (non blocking) you have to set:

label.drawLabels = True

Tested on QGIS 2.18.22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.