4

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:
    attribute=f.['field_name']

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 at 12:44
2

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():
        context.setFeature(feature)
        expression.prepare(context)
        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.