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?
NOTE: The script shouldn't trip an error IF the layer is ABSENT.
len(QgsMapLayerRegistry.instance().mapLayersByName('the_Map_Layer_in_question')) != 0
True
if layer exists, otherwise False
len(...) != 0
and just directly test the returned list, eg if QgsMapLayerRegistry.instance().mapLayersByName('the_Map_Layer_in_question'):
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:
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