I have a python module, where a QGIS memory vector layer is created, within the same method that creates this layer I have constructed labels using:
text_format = QgsTextFormat()
label = QgsPalLayerSettings()
label.fieldName = 'Description'
label.enabled = True
label.setFormat(text_format)
labeler = QgsVectorLayerSimpleLabeling(label)
layer.setLabelsEnabled(True)
layer.setLabeling(labeler)
layer.triggerRepaint()
And then subsequently from another Python module I add this layer to the QGIS workspace using:
QgsProject.instance().addMapLayer(layer)
The labels are not showing in QGIS, however, if I open the "Labels" dialogue from within QGIS and press "Apply" then the labels show. So I assume that the label field and text is set properly.
I have repeated the problem described above in the Python console within QGIS v3.2.2 using the following script:
from qgis.core import *
layer=QgsVectorLayer('MultiLineString?crs=epsg:4326&field=ID:string&field=Description:string', "MultiLines", "memory")
pr=layer.dataProvider()
record = QgsFeature()
record.setAttributes(['1','test'])
record.setGeometry(QgsGeometry.fromWkt('MULTILINESTRING ((1 1, 6 1))'))
pr.addFeature(record)
text_format = QgsTextFormat()
label = QgsPalLayerSettings()
label.fieldName = 'Description'
label.enabled = True
label.setFormat(text_format)
labeler = QgsVectorLayerSimpleLabeling(label)
layer.setLabelsEnabled(True)
layer.setLabeling(labeler)
layer.triggerRepaint()
QgsProject.instance().addMapLayer(layer)
Any suggestions on what I need to add to my python script to have the labels show?
QGIS v3.2.2-Bonn was used.