0

I want to label my vector layer by feature id, When I am trying to do it manually, it works fine but when I write the code below, it stops working and I am unable to label them by feature ID $id.

Code :

pal_layer = QgsPalLayerSettings()
text_format = QgsTextFormat()
text_format.setFont(QFont("Arial", 12))
text_format.setSize(12)
pal_layer.setFormat(text_format)
pal_layer.fieldName = "$id"
pal_layer.enabled = True
pal_layer.placement = QgsPalLayerSettings.Line
labels = QgsVectorLayerSimpleLabeling(pal_layer)
layer.setLabeling(labels)
layer.setLabelsEnabled(True)
layer.triggerRepaint()

If I use any other attribute from the table, this code works fine, but my requirement is labeling them by feature id $id, this works fine when I manually type $id in value, but using code I am having no luck.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jun 15, 2021 at 7:50

1 Answer 1

3

According to the doc for QgsPalLayerSettings.fieldName,

If fieldName is an expression, then isExpression should be set to true.

So, as $id is not a column name but and expression, add

pal_layer.isExpression = True
answered Jun 15, 2021 at 9:05

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.