1

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?

1

You need this:

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

, or

label.drawLabels = True

You choose.

1

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.