Query list of layers an run code on each layer

I want to query all opened layers in my QGIS project and then run an algorithm on each of the opened layers.

layers_list = []
layers_list = QgsProject.instance().mapLayers().values()
name_field = 'Admin_name'

for layer in layers_list:
   name = [f[name_field] for f in layers_list.getFeatures()[0]
   .... do something smart ....

It always throws me an error: ‘dict_value’ object has no attribute ‘getFeatures’

I m aware that the list only contains the names of the opened layers an no direct pointer to that layer – but how can i achieve that my for– loop goes through all the layers?

Geographic Information Systems Asked on November 21, 2021

1 Answers

One Answer

Bellow, following @IanTurton comments, is a right way to do this :

layers_list = QgsProject.instance().mapLayers().values()
name_field = "Admin_name"

for lyr in layers_list:
    name_data = [f[name_field] for f in lyr.getFeatures()]
    # .... do something smart ....


QgsProject.instance().mapLayers().values() list all layers (vector and raster) in the current QGIS project, so, layers_list contains a list of QgsMapLayer.

In the for loop, we affect lyr an item at a time for each item in the layers_list, so, lyr is a project QgsMapLayer at each loop.

QgsMapLayer.getFeatures() gets all the features of a layer, and we can access to each "Admin_name" values with f["Admin_name"] if f is the current QgsFeature in the comprehension list loop.

p.s. : yes, the QGIS cookbook is your friend !

Answered by J. Monticolo on November 21, 2021

Add your own answers!

Related Questions

Does QGIS use data source-specific operations?

0  Asked on December 30, 2020 by geotob


Writing Non Spatial Table into Geopackage – Python

2  Asked on December 30, 2020 by jamesleversha


GeoServer blocked HTTP requests issue

1  Asked on December 30, 2020 by peterzhu


Displaying map title in PyQGIS

1  Asked on December 29, 2020 by marcelo-freitas


Cancel event in Python Gp tools with arcpy

3  Asked on December 29, 2020 by user17515


Center Text In Table Column

3  Asked on December 29, 2020 by slywhitesheep


SELECT * will not work with table containing geodata

1  Asked on December 29, 2020 by fred-randall


Ask a Question

Get help from others!

© 2021 All rights reserved.