6

I have a list ("datList") with names of raster layers which I want to add. When I add raster layers in the Python Console everything works fine:

for da in datListe:
   layerDir = "C:/[path]/" + da
   iface.addRasterLayer(layerDir,da)

When I do the same in a processing script with...

for da in datListe:
   layerDir = "C:/[path]/" + da
   rlayer = QgsRasterLayer(layerDir,da)
   QgsProject.instance().addMapLayer(rlayer) 

the layers are not added to my map. However, they seem to be in the project as

QgsProject.instance().mapLayers()

(typed in the Python Console) prints a list with the desired layers

PolyGeo
  • 65,136
  • 29
  • 109
  • 338

2 Answers2

0

Layers created during the run of a processing are in a separate instance, not the main one you see. You must load them at the end of the script with:

for da in datListe:
   layerDir = "C:/[path]/" + da
   rlayer = QgsRasterLayer(layerDir,da)
   context.temporaryLayerStore().addMapLayer(rlayer)
   context.addLayerToLoadOnCompletion(rlayer.id(), QgsProcessingContext.LayerDetails("", QgsProject.instance(), ""))

context is normally a variable containing the QgsProject.instance() of the main thread... if I understand this correctly.

For an alternative method that run the processing script in the main tread instead of a separate one see https://gis.stackexchange.com/a/280514/109610

0

I think that the raster layer may not display properly if the project's crs is not set.

QgsProject.instance().crs()
# <QgsCoordinateReferenceSystem: invalid>

Setting crs might help.

QgsProject.instance().setCrs(QgsCoordinateReferenceSystem("EPSG:3857"))

(Set the EPSG value to suit your project)

unicalm
  • 3
  • 3