The expression box has a handy "select from selection" button. Is there a way to emulate this with python? I have the basic expressions down, but can't find a way to do this.

  • 1
    Something unexpected came up so I had to deal with that first.. but I tested your solution just now. Works great! – MapEngine Mar 3 '15 at 19:34

I didn't find the option from the API, but you could mimic such behavior this way:

I assume there are selected features already, so get their Ids:

lyr = iface.activeLayer()
selIds = lyr.selectedFeaturesIds()

You said you have an expression, let's say:

expr = QgsExpression( "\"NMG\" = 'CALI'" )

Now, get feature Ids that match your expression:

it = lyr.getFeatures( QgsFeatureRequest( expr ) )
newIds = [i.id() for i in it]

Get only those that are already selected and match your expression (this is the magic part):

idsToSel = list( set(selIds).intersection(newIds) )

Finally, select them:

lyr.setSelectedFeatures( idsToSel )
  • 1
    setSelectedFeatures should work up to QGIS2.16 but will be/has been deprecated in newer versions. See here. New coders should try this instead: lyr.selectByIds( idsToSel ) – weiji14 Aug 10 '16 at 1:53
  • That's right, thanks! There are upcoming API changes that will make tons of GIS.SE answers obsolete. – Germán Carrillo Aug 10 '16 at 13:32

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.