5

How do you apply a QgsExpression to a Label ?

I can do it in QGIS with this simple expression concat('N:' ,round(Value,0),'\n','Yield:' ,round(Value 2,0))

N: 65

Yield: 40

How do I do it in PyQGIS ? I see a getLabelExpression but no setLabelExpression

This works but I want but only for the field name

 crap = QgsVectorLayer("D:/data.shp", "data", "ogr")
 QgsMapLayerRegistry.instance().addMapLayer(crap)
 palyr = QgsPalLayerSettings()
 palyr.readFromLayer(crap)
 palyr.enabled = True
 palyr.fieldName = 'Name'
 palyr.placement= QgsPalLayerSettings.OverPoint
 palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'8','')
 palyr.writeToLayer(crap)

2 Answers 2

5

Place the expression in palyr.fieldName, then set palyr.isExpression to True:

palyr = QgsPalLayerSettings()
palyr.readFromLayer(crap)
palyr.enabled = True
palyr.fieldName = "concat('N:' ,round(Value,0),'\\n','Yield:' ,round(Value 2,0))"
palyr.isExpression = True
palyr.placement= QgsPalLayerSettings.OverPoint
0
3

Here's a working snippet for creating some label settings and labelling with an expression for PyQGIS 3:

# Define layer object
layer = QgsProject().instance().mapLayersByName('Name_of_your_layer')[0]

settings = QgsPalLayerSettings()
format = QgsTextFormat()
format.setFont(QFont('Arial', 8))
format.setColor(QColor('Black'))
buffer = QgsTextBufferSettings()
buffer.setEnabled(True)
buffer.setSize(0.50)
buffer.setColor(QColor('grey'))
format.setBuffer(buffer)
settings.setFormat(format)
settings.fieldName = """concat("field_1", ' ', "Field_2")"""
settings.isExpression = True
labels = QgsVectorLayerSimpleLabeling(settings)
layer.setLabelsEnabled(True)
layer.setLabeling(labels)
layer.triggerRepaint()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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