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

0

2 Answers 2

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.