TransWikia.com

Selecting from selection with PyQGIS

Geographic Information Systems Asked on July 5, 2021

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.

2 Answers

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 )

Correct answer by Germán Carrillo on July 5, 2021

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.

Answered by Филипп Утин on July 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP