Visible layers
You can iterate visible layers in this way:
# Iterate visible layers (warning: only spatial ones)
def iterate_visible_layers():
for layer in iface.mapCanvas().layers():
# TODO: Do something interesting with the layers
print(layer.name())
iterate_visible_layers()
Layers in TOC (layers panel / legend / layer tree)
In case that you need all layers in the TOC/Layers-panel (not only those that are visible/checked, as mapCanvas().layers()
returns), you can use this function:
# Iterate all ToC layers (warning: only spatial ones)
def iterate_toc_layers(group):
for tree_layer in group.findLayers():
# TODO: Do something interesting with the layers
print(tree_layer.layer().name())
root = QgsProject.instance().layerTreeRoot()
iterate_toc_layers(root)
Note: You can iterate layers from a specific group by passing such a group to iterate_toc_layers()
, in this way:
my_group = root.findGroup('My group')
iterate_toc_layers(my_group)
All registered layers
QGIS can use layers that are part of the QGIS project but are not shown in the TOC/Layers-panel. For instance, layers that can be used in joins or relationships (look-up tables). If you want to get those layers listed as well, do this:
# Iterate all registered layers (even if they aren't in the TOC)
def iterate_all_layers():
for k, layer in QgsProject.instance().mapLayers().items():
# TODO: Do something interesting with the layers
print(layer.name())
iterate_all_layers()