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.
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 )
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.