0

I have a script from List index out of range when put in startup.py on QGIS :

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)

I want to put the script in startup.py. So when load QGIS, 'pl.shp' layer will be selected.

With this script, there is notification to save project or not. I have read to remove notification in Remove saving notification when use python QGIS at startup. Then I add the script in Remove saving notification when use python QGIS at startup. But, there is still notification. So, how to combine two script without saving notification?

0

As in the linked posts you gave, you need to use the script from this post to do something after QGIS has finished initialising.

So the minimum code you need to use would be:

from qgis.utils import iface

def load_function():
    print "Let's do something!"

iface.initializationCompleted.connect(load_function)

All the above code does is once QGIS is loaded completely, it will run the function (in this case, print a message in the python console). So all you would need to do is replace the message with your code. Also note that you may be required to import additional classes in your script. For example, if you try to load a vector layer during startup, you might get an error message saying:

QgsVectorLayer is not defined.

To find out which module the QgsVectorLayer class belongs to, you can type help(QgsVectorLayer) or just QgsVectorLayer to see that it belongs to qgis.core.

So then we can add from qgis.core import QgsVectorLayer at the top (much more efficient than using from qgis.core import *). Then repeat for all other required classes.


The final code could look something like this:

from qgis.core import QgsMapLayerRegistry, QgsVectorLayer
from qgis.utils import iface

def load_function():
    layer =  QgsVectorLayer('path/to/layer', 'pl' , 'ogr')
    QgsMapLayerRegistry.instance().addMapLayer(layer)
    vl = QgsMapLayerRegistry.instance().mapLayersByName('pl')[0]
    iface.setActiveLayer(vl)

iface.initializationCompleted.connect(load_function)
  • 1
    Ok it is work. I use : layer = QgsVectorLayer('%~dp0DATA/PROJECT', 'pl' , 'ogr') in relative path. – mega Mar 7 '17 at 23:50
  • @mega - Glad it worked :) – Joseph Mar 8 '17 at 9:49

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.