In QGIS, what is the simplest Python code (least possible) to verify if a particular layer is PRESENT or ABSENT in the Map Layers list?
The script shouldn't trip an error IF the layer is ABSENT.
asked Jan 3, 2016 at 14:24
3 Answers 3
len(QgsMapLayerRegistry.instance().mapLayersByName('the_Map_Layer_in_question')) != 0
True
if layer exists, otherwise False
answered Jan 3, 2016 at 16:41
-
7note that you could avoid the
len(...) != 0
and just directly test the returned list, egif QgsMapLayerRegistry.instance().mapLayersByName('the_Map_Layer_in_question'):
ndawson– ndawson2016年01月04日 03:12:00 +00:00Commented Jan 4, 2016 at 3:12
For QGIS 3.x versions
In QGIS 3.x the functionality of QgsMapLayerRegistry
has been moved to QgsProject
, so in PyQGIS 3 you need this:
layers = QgsProject.instance().mapLayersByName("the_Map_Layer_in_question")
exist = True if layers else False
print(exist)
References:
MrXsquared
36.2k22 gold badges76 silver badges127 bronze badges
answered Jun 8, 2020 at 10:18
boolean = False
layers = QgsMapLayerRegistry.instance().mapLayers()
for name, layer in layers.iteritems():
if layer.name() == ('the_Map_Layer_in_question'):
boolean = True
# if the map layer exists boolean == True, if it doesn't boolean == False
answered Jan 3, 2016 at 15:24
lang-py