PyQGIS – Checking If a Feature is Selected When Iterating Over a Vector Layer

pyqgisselect

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()
provider.select(allAttrs)
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.

Best Answer

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 feat.id() 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()
vlayer.select([], QgsRectangle(), False)
set_allids = set()
while vlayer.nextFeature(feat):
    set_allids.add(feat.id())

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 QgsVectorLayer.select() and iterate with QgsVectorLayer.nextFeature()).


I updated the 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.

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