I need get the label text for each feature in a points layer. I can read feature attribute using:

layer = QgsProject.instance().mapLayersByName('layer_name')[0]
features = layer.getFeatures(QgsFeatureRequest())
for f in features:

but I need the label text (result of a expresion), it's diferent from attribute.

  • U mean u're labeling with an expression ? – snaileater Jun 6 '19 at 12:44

You can get the label text for each feature this way in QGIS 3:

layer = iface.activeLayer()

if layer.labelsEnabled():
    labeling = layer.labeling()
    palyr = labeling.settings()
    expression = QgsExpression(palyr.fieldName)

    context = QgsExpressionContext()
    for feature in layer.getFeatures():
        value = expression.evaluate(context)
        print(expression.formatPreviewString(value, True))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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