0

I add a vector layer to a map with

QgsMapLayerRegistry.instance().addMapLayer(self.vlayer)

later the attributes are read with

def select_all(layer):
layer.select([])
layer.setSelectedFeatures([obj.id() for obj in layer])

and

layer = self.vlayer
select_all(layer)
dict={}

for elem in layer.selectedFeatures():
    attrs = elem.attributeMap()
    for (k,v) in attrs.iteritems():
        dict.update({k:v})

The problem is that it selects all the feature in the map, too (which highlights them yellow). I tried to use

layer = self.vlayer
layer.select()
dict={}

for elem in layer:
   attrs = elem.attributeMap()
    for (k,v) in attrs.iteritems():
        dict.update({k:v})

but i get only an empty dictionary. Is it possible to get the values without selecting everything?

1

You don't need to select any of the features on the map. This is all you need to loop over all the features in a layer with all their attributes:

layer = self.vlayer
provider = layer.dataProvider()
layer.select(provider.attributeIndexes())
for feature in layer:
   print feature.attributeMap()

There are few overloaded calls to select() this is the one you need to use http://qgis.org/api/1.8/classQgsVectorLayer.html#a13c6551c0b96da88004904d584599185

Note: This select() method has been removed from QGIS 2.0 and is replaced with:

for feature in layer.getFeatures():
    print feature
  • attributeMap() returns a dict of field index : value – Nathan W Jul 11 '13 at 9:51
  • Ok thanks. It is working. Had a little mistake in the code. – Martin Jul 11 '13 at 9:51

Your Answer

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

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