4

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.

4
  • 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, 2015 at 19:34
  • 1
    You could try to use your ids with request.setSubsetOfAttributes .
    – Matte
    Sep 4, 2017 at 9:33
  • 1
    For anyone testing this on QGIS < 2.99, they should use ids = vl.selectedFeaturesIds() instead :)
    – Joseph
    Sep 4, 2017 at 9:49
  • @Matte do you suggest to use request.setSubsetOfAttributes with the first request?
    – matteo
    Sep 4, 2017 at 11:43

2 Answers 2

6

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 )
2
  • 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, 2016 at 1:53
  • That's right, thanks! There are upcoming API changes that will make tons of GIS.SE answers obsolete. Aug 10, 2016 at 13:32
1

To select from the selected objects (filter the current selection) in QGIS 3, I used IntersectSelection, it Modify current selection to include only select features which match.

layer = self.iface.activeLayer()
myExpression = '\"population\" > 100'
layer.selectByExpression(myExpression, QgsVectorLayer.IntersectSelection)

From the current selection, only objects with a population greater than 100 will remain selected. If there was no current selection, then no objects will be selected.

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.