Bug report #15723

Labels not showing when adding them using Python

Added by Casper Børgesen about 8 years ago. Updated over 5 years ago.

Status:Closed
Priority:Normal
Assignee:-
Category:PyQGIS Console
Affected QGIS version:master_2 Regression?:No
Operating System: Easy fix?:No
Pull Request or Patch supplied:No Resolution:end of life
Crashes QGIS or corrupts data:No Copied to github as #:23645

Description

I have a simple vector polygon layer with one feature. Using python I create a simple label displaying the area of the feature.

Expected result:
A square with a label saying "1".

Actual result:
A square without a label.

Try:
Right click the layer and select properties. Click the apply button and the label is now being shown. Since no changes were made in the properties window, I would expect the label not to be shown if this was not a bug. But since the label was shown by pressing the apply button without any changes made to the properties, it seems to me that it is a bug.

Question:
Why is the label not shown using the below code?

Affects:
I have tested the code using QGIS 2.14.7, 2.16.1, master_2 (7396370) on Windows 7 x64, and a recent master_2 on Ubuntu x64.

from qgis.core import *
layer = QgsVectorLayer('Polygon', 'my layer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(layer, True)
geom = QgsGeometry.fromWkt('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))')
feature = QgsFeature()
feature.setGeometry(geom)
layer.startEditing()
layer.addFeature(feature)
layer.commitChanges()

label = QgsPalLayerSettings()
label.readFromLayer(layer)
label.enabled = True
label.fieldName = 'round($area,0)'
label.drawLabels = True
label.writeToLayer(layer)

History

#1 Updated by Casper Børgesen about 8 years ago

Can I ask someone to change the Category from "PyQGIS Console" to "Python plugins and bindings" since I think that label is more exact?

I don't seem to have the necessary rights to change my own issues.

#2 Updated by Giovanni Manghi over 7 years ago

  • Easy fix? set to No
  • Regression? set to No

#3 Updated by Giovanni Manghi over 5 years ago

  • Resolution set to end of life
  • Status changed from Open to Closed

Also available in: Atom PDF