In my script I want to open layer named my_layer if it is in the map layer registry. I use following code for it:

inputLayer = QgsMapLayerRegistry.instance().mapLayersByName("my_layer")[0]

If not found, I add it to the registry from file. However, if there are no layers in the registry, it returns an "out of bounds" error - mapLayersByName produces empty list with no first element (mapLayersByName("my_layer")[0]). How to avoid the error? Is catching it the only option, or can I detect empty registry before?

I'm new to Python and PyQGIS, so it's quite probable that I've missed something in my previous steps and that there's some more elegant way to load the layer without stacking instances of the same layer in the registry. If it's so, I'm interested both in the more elegant way to solve this task and in the way how to detect the empty map layer registry (I suspect I will need both later).


You could loop through the the Layers panel to check if the layer exists or not by the name before assigning:

layers = QgsMapLayerRegistry.instance().mapLayers().values()
foundLayer = False
for layer in layers:
    if layer.name() == 'my_layer':
        inputLayer = QgsMapLayerRegistry.instance().mapLayersByName("my_layer")[0]
        foundLayer = True

if not foundLayer:
    # add layer from file

Or you could simply use a try/except logic

    inputLayer = QgsMapLayerRegistry.instance().mapLayersByName("my_layer")[0]
except IndexError:
    print 'layer not in map add from file'
    # add from file
| improve this answer | |
  • The second method is the best and fastest. – Nathan W Jul 30 '15 at 12:54

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.