dimanche 26 avril 2009

QGIS routine: get the attribute values of selected features

Here, we'll learn how to access the values of a layer's selected features.

The retrieval of these values deserves many uses:
Statistics:
-some aggregation operations like sum, average, whatever...

Actions:
-Opening a picture related to a ponctual object
-Opening a web browser which URL includes one or more attribute values

Outputs:
-Export the values of selected features in a PDF report
-Opening a spreadsheet with these values so as to make graphs.

Notice: most of the actions mentionned above can also be accomplished using the QGIS actions that you access through the layer's properties.

Here is the QGIS routine that will allow you to access the attribute values of the active layer's selected features:

>>> myLayer=iface.activeLayer()
>>> objects=myLayer.selectedFeatures()
>>> objets.attributeMap()
>>> object=objects[0]
>>> attributes=object.attributeMap()
>>> attributes[0].toString()
"Bonifacio"

>>> objects=myLayer.selectedFeatures()
it returns a list of the selected objects
>>> attributes=object.attributeMap()
This attributeMap() method allows you to get the attribute values of the object you considered, in our case, the first one (object=object[0]).
It returns a dictionary which each key is an auto-incremented number. Notice that, unfortunately, the key is not the attribute name.
>>> attributes[0].toString()
Each value of the attributes is QString object. The method toString() makes it readable for the user. Here, we get the the first attribute's value.

Most often, you would combine the previous "attribute name" routine with this one.