Here, we’ll learn how to access the values of a layer’s selected features.
The retrieval of these values deserves many uses:
-some aggregation operations like sum, average, whatever…
-Opening a picture related to a ponctual object
-Opening a web browser which URL includes one or more attribute values
-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:
it returns a list of the selected objects
This attributeMap() method allows you to get the attribute values of the object you considered, in our case, the first one (object=object).
It returns a dictionary which each key is an auto-incremented number. Notice that, unfortunately, the key is not the attribute name.
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.
Imagine you’d like to create a plugin that searches objects depending on their attributes.You’d like to display the layer fields in a combobox but how to get them?
The code shown below is often used in plugins and allows you to get the curent layer’s fields.
fieldmap is a list of values containing your field names.
If you want to get the name of the ith field, just type fieldmap[i] in the QGIS python console.
Maybe now you’ve learned how to get the layer fields, you’d like to know their values. It’ll be the purpose of the next post.
Get the current layer
Often, you’ll have to perform operations on the active layer.
Before performing these operations, you first have to identify it and get it.
Once you have it, you can perform all the operations you’ll want.
In the following lines, i’ve included print statements so as to check the content of my variables.
>>> print mycurrentlayer.getLayerID()
>>> print mycurrentlayer.name()
Firts of all, put the canvas in the variable mc.
Once you have your canvas, get its current layer called mycurrentlayer.
You can see some methods have been applied to the layer:
- the method getLayerID()
- the method name()
The layer name is only useful when displayed.
The layer id is often used whe performing operations on the layer.
Get a layer according according to its position in the legend
The method getZpos allows you to get a layer according to its position in the legend.
This kind of routine is often used when you need to get layers with their indexes