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?

asked Sep 29, 2016 at 7:46
5
  • Have you checked this answer? gis.stackexchange.com/questions/136526/… Commented Sep 29, 2016 at 13:50
  • How are you defining my_layer? Commented Sep 30, 2016 at 12:07
  • @Germán Carrillo, I have and thats why I tried the setCustomProperty approach. 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. Commented Oct 3, 2016 at 6:10
  • I have created an issue for this: hub.qgis.org/issues/15723 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.

tinlyx
11.3k18 gold badges78 silver badges130 bronze badges
answered Nov 14, 2016 at 23:46
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

answered Jul 23, 2018 at 11:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.