PyQGIS – Fixing ‘List Index Out of Range’ Error in QGIS Startup.py

pyqgis

I have the code :

from qgis.core import QgsMapLayerRegistry
vl = QgsMapLayerRegistry.instance().mapLayersByName('pl')[0]
iface.setActiveLayer(vl)

When I type in console after loading QGIS, no error. But, when I put the code in startup.py, so automatically QGIS will execute the code in startup.py, I get error. The error : "list index out of range"

What is wrong for the code?

Best Answer

You probably need to preliminarily import the layer before calling it.

If pl is a shapefile:

from qgis.core import *
layer =  QgsVectorLayer('C:/Users/path_to_shapefile/vector_layer.shp', 'pl' , "ogr")
QgsMapLayerRegistry.instance().addMapLayer(layer)
vl = QgsMapLayerRegistry.instance().mapLayersByName('pl')[0]
iface.setActiveLayer(vl)

If pl is a raster:

from qgis.core import *
layer =  QgsRasterLayer('C:/Users/path_to_raster/raster_layer.tif', 'pl')
QgsMapLayerRegistry.instance().addMapLayer(layer)
vl = QgsMapLayerRegistry.instance().mapLayersByName('pl')[0]
iface.setActiveLayer(vl)
Related Question