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:

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)

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 ?


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.

| improve this answer | |
  • simple like that! thanks! Do you have a good source so I could study more about this? – caio villaca Jun 18 '19 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.