0

How can I use this field calculator expression in PyQGIS? Right now i have the following code. It generates a new field but it does not fill the field. (see bottom for layer example)

layer = iface.activeLayer()

pv = layer.dataProvider()
pv.addAttributes([QgsField('Count', QVariant.Double)])

layer.updateFields()

expression1 = QgsExpression('array_length(overlay_nearest(PND_Aangrenzend,"",limit:=10,max_distance:=5))')

context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))

with edit(layer):
    for f in layer.getFeatures():
        context.setFeature(f)
        f['Count'] = expression1.evaluate(context)
        layer.updateFeature(f)

enter image description here

2
  • Welcome to GIS SE! We're a little different from other sites; this isn't a discussion forum but a Q&A site. Your questions should as much as possible describe not just what you want to do, but precisely what you have tried and where you are stuck trying that. Please check out our short tour for more about how the site works
    – Ian Turton
    Commented Sep 5, 2022 at 15:49
  • If you are ok with creating a new layer: Execute the Field Calculator from processing toolbox, go to History Ctrl+Alt+H, copy the command
    – Bera
    Commented Sep 5, 2022 at 17:24

1 Answer 1

2

I am not sure what the wider context of your question is, but you can use expressions in QGIS like so:

layer.selectByExpression(expression)

This may mean that you can use your expression like so:

layerName = "layerNameGoesHere"
layer = QgsProject.instance().mapLayersByName(layerName)[0]
expression = f'array_length(overlay_nearest( @layer ,"",limit:=10,max_distance:=5))'
layer.selectByExpression(expression)
1
  • I want to count the adjacent features with pyqgis instead of the field calculator Commented Sep 6, 2022 at 7:18

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.