6

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.

12
len(QgsMapLayerRegistry.instance().mapLayersByName('the_Map_Layer_in_question')) != 0

Trueif layer exists, otherwise False

  • 2
    note that you could avoid the len(...) != 0 and just directly test the returned list, eg if QgsMapLayerRegistry.instance().mapLayersByName('the_Map_Layer_in_question'): – ndawson Jan 4 '16 at 3:12
4
 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.