4

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?

  • 3
    Generally it means you are calling something that doesn't exist. So I assume when you have QGIS open and use the console, your object exists, but when you call your code in startup.py the object doesn't yet exist... – nmtoken Mar 2 '17 at 8:14
4

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)
  • 2
    Nice answer! I would just like to add that when adding any layers from the startup.py script, it is probably best to define a function which loads the layers and run this function when QGIS has finished the initialisation process as was asked in this post. Otherwise the annoying notification message appears :) – Joseph Mar 3 '17 at 11:31
  • It is work. But, there is annoying notification as in this post : gis.stackexchange.com/questions/226298/…. I can not combine the code to remove notification. Should I ask a new question? – mega Mar 6 '17 at 1:32
  • @mega I think you are asking some help for a new topic. Assuming that it's not a duplicate of the question in the link that you shared, I suggest you accepting this answer (it seems it solved the error: "list index out of range") and asking a new question. – mgri Mar 6 '17 at 13:43

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.