6

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.

Taras
35.8k5 gold badges77 silver badges152 bronze badges
asked Dec 22, 2017 at 13:53

1 Answer 1

4

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.

Taras
35.8k5 gold badges77 silver badges152 bronze badges
answered Dec 24, 2017 at 11:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.