1

I need to run a for loop to select features by their attributes, because the values are within lists (strkey and strvalue). I'm using the following script:

k=0
v=0
layer = iface.activeLayer()
for item in keys:
    listk = strkey[k]
    listv = strvalue[v]
    layer.selectByExpression('\"LINE_ID\" IN ('+listk+') AND \"Declividad\" IN ('+listv+')', QgsVectorLayer.SetSelection)
    v=v+1
    k=k+1

The problem is that only the last feature is selected. Is like every loop the Qgis erases the old selection to select the new feature. Is there a way to accumulate the selections ?

2

The reason why your selections are being overwritten on each iteration is because you passed QgsVectorLayer.SetSelection for the SelectBehaviour parameter. This sets a new selection each time, removing any existing selection.

Changing your SelectBehaviour argument to QgsVectorLayer.AddToSelection should do the trick.

  • simple like that! thanks! Do you have a good source so I could study more about this? – caio villaca Jun 18 at 12:27

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.