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 thefeat.id()
is invlayer.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:
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 withQgsVectorLayer.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.