I'm facing a nested problem using pyqgis (for QGIS master, but it can be replicated in any version of QGIS 2).

I have a vector layer with some selected features and with a QgsFeatureRequest I can easily loop only on the selected features:

vl = iface.activeLayer()
# get the list of selected ids 
ids = vl.selectedFeatureIds()

# create the request with the selected ids
request = QgsFeatureRequest()

# use only the selected features in getFeatures
for i in vl.getFeatures(request):

Then I build an expression based on a field of the attribute table and I can use QgsFeatureRequest() to filter only the features that match that expression:

exp = ''' "Piper" = 1 '''
request = QgsFeatureRequest()

for i in vl.getFeatures(request):

but what if I want to filter with the same expression only the already selected features?

So actually use both requests in the same getFeatures loop?

  • 1
    You could try to use your ids with request.setSubsetOfAttributes . – Matte Sep 4 '17 at 9:33
  • 1
    For anyone testing this on QGIS < 2.99, they should use ids = vl.selectedFeaturesIds() instead :) – Joseph Sep 4 '17 at 9:49
  • @Matte do you suggest to use request.setSubsetOfAttributes with the first request? – matteo Sep 4 '17 at 11:43
  • I agree it could be a handy option in the QGIS API, but you can also use the answer to How to select from selection with PyQGIS? – Germán Carrillo Oct 6 '17 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.