I am creating a QGIS plugin. Loaded postGIS layers onto QGIS. now, 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.
Answer
To get names and indices of attributes use fieldNameMap()
. 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.
No comments:
Post a Comment