Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

While iterating over a vector layer using the following code (summerized from the example in the pyqgis cookbook), is there a way to check whether a feature is selected?

provider = vlayer.dataProvider()
feat = QgsFeature()
allAttrs = provider.attributeIndexes()
while provider.nextFeature(feat):
    geom = feat.geometry()
    attrs = feat.attributeMap()
    for (k,attr) in attrs.iteritems():
        print "%d: %s" % (k, attr.toString())

Alternatively, I could create a list of selected features using vlayer.selectedFeatures(), but I'm hoping there is a way to check each feature directly.

share|improve this question
up vote 8 down vote accepted

There doesn't seem to be a way to directly find a feature object's parent layer or whether it's selected from a method in the QgsFeature class.

A similar approach to vlayer.selectedFeatures() is to test whether the is in vlayer.selectedFeaturesIds(). QgsFeatureIds are not unique values compared with other vector layers, only within their own layer.

Alternatively, you could start with vlayer.selectedFeatures() and iterate over those features, instead of all features of the provider.

Yet another approach is to initially gather sets (or lists) of selected and non-selected feature ids for a given vector layer:

# previous relevant code

set_selids = set(vlayer.selectedFeaturesIds())
feat = QgsFeature()[], QgsRectangle(), False)
set_allids = set()
while vlayer.nextFeature(feat):

set_notselids = set_allids - set_selids

print set_allids
print set_selids
print set_notselids

I can't seem to find a single call for retrieving a reference to all features (or ids) for a vector layer (i.e. still have to use and iterate with QgsVectorLayer.nextFeature()).

Edit: updated code to reflect QgsVectorLaer can handle select call (no need to get provider directly), and doesn't mess up actual selected features in map canvas, which would require setSelectedFeatures() to update.

Edit 2: after building feature id sets, you can iterate over them and use QgsVectorLayer.featureAtId(featid) to access the feature.

share|improve this answer
I suspected that might be the case, but thanks very much for the helpful suggestions. – Cyrus Aug 6 '12 at 0:54

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.