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))

pal_layer.fieldName = "$id"
pal_layer.enabled = True
pal_layer.placement = QgsPalLayerSettings.Line
labels = QgsVectorLayerSimpleLabeling(pal_layer)

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.

1 Answer 1


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

Your Answer

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

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