[GIS] Iterating over map layers using PyQGIS

iterationlayerspyqgis

I'm having trouble figuring out how to iterate over map layers. I can access the currently highlighted layer in the table of contents via iface.activeLayer() but I want my code to operate on all layers.

I don't see anything in the API that provides easy access to this functionality and couldn't find a good online example but maybe I missed something?

Best Answer

Try...

# substitute 'self' with 'qgis.utils.iface' when run from Python console
# 'self.iface = iface' would usually precede this command in your class 
layers = self.iface.legendInterface().layers()

for layer in layers:
    layerType = layer.type()
    if layerType == QgsMapLayer.VectorLayer:
        # do some stuff here

Culled from consolidatethread.py from QConsolidate plugin.

Description of QgsLegendInterface object returned from legendInterface().

Edit: added info on 'self' above.