16

I need a list containing the names of all the layers in a QGIS session. I did the task as

layersNames = []
for i in self.iface.mapCanvas().layers():
   layersNames.append(str(i.name()))

but this has the problem that only the names for the visible layers are extracted. How can I get a list with the names of all (visible or not) layers using PyQGIS?

RafDouglas C. Tommasi
  • 6,479
  • 1
  • 15
  • 41
jgpallero
  • 749
  • 2
  • 8
  • 17

2 Answers2

29

Since version 3, QgsMapLayerRegistry funcionalities have been moved to QgsProject: https://qgis.org/api/api_break.html

Update for QGIS3.x:

from qgis.core import QgsProject

names = [layer.name() for layer in QgsProject.instance().mapLayers().values()] print(names)

as per @Nathan W's answer, this produces a list of layers in the current project:

['GoogleSat', 'MyPointsLayer', 'Roads', 'House_numbers']
Taras
  • 32,823
  • 4
  • 66
  • 137
RafDouglas C. Tommasi
  • 6,479
  • 1
  • 15
  • 41
19

QgsMapLayerRegistry.instance().mapLayers() will give you all layers that are opened.

If you want the names then:

names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values()]

names will be a list of layer names

or using a normal function:

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    print layer.name()
Taras
  • 32,823
  • 4
  • 66
  • 137
Nathan W
  • 34,706
  • 5
  • 97
  • 148
  • Is there any way of listing down the layers from qgis project (.qgz) by mentioning the filename ? in other words, I want to loop over list of files and list down all the layers ? – Kavyajeet Bora Oct 31 '22 at 10:20