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?

5
  • Have you checked this answer? gis.stackexchange.com/questions/136526/… Commented Sep 29, 2016 at 13:50
  • How are you defining my_layer?
    – artwork21
    Commented Sep 30, 2016 at 12:07
  • @Germán Carrillo, I have and thats why I tried the setCustomProperty approach.
    – Chau
    Commented Oct 3, 2016 at 6:09
  • @artwork21, I have updated my question to answer your question. But I don't think any magic is hidden there.
    – Chau
    Commented Oct 3, 2016 at 6:10
  • I have created an issue for this: hub.qgis.org/issues/15723
    – Chau
    Commented Oct 19, 2016 at 11:39

2 Answers 2

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 and acknowledge you have read our privacy policy.

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