I am creating a QGIS plugin. Loaded PostGIS layers into QGIS. Now, I need to iterate the feature attributes with next and previous buttons. Once the layer is loaded, first attribute and feature is selected.
feature = selectedLayer.getFeatures().next()
selectedLayer.setSelectedFeatures([feature.id()])
Using this code, first attribute and feature is selected. I am struck in selecting the next attribute of feature using next button.
1 Answer 1
To get names and indices of attributes use the fieldNameMap()
method. In the following example I use a layer with three attributes.
prov = selectedLayer.dataProvider()
fnm = prov.fieldNameMap()
# >>> fnm
# {u'fieldstr': 2L, u'fieldflt': 1L, u'fieldint': 0L}
fnm
maps field names to their field index. Now you are able to iterate over the attributes of selected features using this information.
For your convenience do a reverse mapping of the field name map to a field index map.
fim = {index: name for name, index in fnm.items()}
Now you are able to access field names and attribute values using field indices.
for i in fim:
print fim[i], feature[i]
fieldint 1
fieldflt 2.0
fieldstr String
Use the Next Button to iterate from 0 to len(fim) - 1
and retrieve the information you are looking for.
Explore related questions
See similar questions with these tags.