TransWikia.com

Get layer by name, retrieve layer, in startup.py

Geographic Information Systems Asked by vitorcsm on August 12, 2021

I wrote a simple script in startup.py, but when I open a QGIS project, I appear a python error window.
The "contratos" layer is a PostGIS layer. But I tried with a regular layer and the error persist.

Code:

from qgis.core import QgsProject
layer = QgsProject.instance().mapLayersByName("contratos")[0]

The Python error notification:

An error occurred during execution of following code:
spec.loader.exec_module(module)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 728, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "C:/Users/vitor.machado/AppData/Roaming/QGIS/QGIS3/startup.py", line 2, in 
    layer = QgsProject.instance().mapLayersByName("contratos")[0]
IndexError: list index out of range
Python version:
3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
QGIS version:
3.8.3-Zanzibar 'Zanzibar', 685d8b15d2
Python path:
['C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python', 'C:/Users/vitor.machado/AppData/Roaming/QGIS/QGIS3profilesdefault/python', 'C:/Users/vitor.machado/AppData/Roaming/QGIS/QGIS3profilesdefault/python/plugins', 'C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins', 'C:PROGRA~1QGIS3~1.8binpython37.zip', 'C:PROGRA~1QGIS3~1.8appsPython37DLLs', 'C:PROGRA~1QGIS3~1.8appsPython37lib', 'C:PROGRA~1QGIS3~1.8bin', 'C:PROGRA~1QGIS3~1.8appsPython37', 'C:PROGRA~1QGIS3~1.8appsPython37libsite-packages', 'C:PROGRA~1QGIS3~1.8appsPython37libsite-packageswin32', 'C:PROGRA~1QGIS3~1.8appsPython37libsite-packageswin32lib', 'C:PROGRA~1QGIS3~1.8appsPython37libsite-packagesPythonwin', 'C:/Users/vitor.machado/AppData/Roaming/QGIS/QGIS3profilesdefault/python']

One Answer

You get this error message when QGIS can't identify your layer. Your layer should not be loaded.

You can write your command line in a function that runs when QGIS initialization is completed. You can follow the following example :

from qgis.utils import iface
from qgis.core import QgsProject


## Function
def your_layer():
    layer = QgsProject.instance().mapLayersByName("contratos")[0]

## When the initialization of QGIS is complete, we launch the your_layer function
iface.initializationCompleted.connect(your_layer)

Correct answer by Vincent Bré on August 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP