1

I'm trying to load a raster tif file using python qgis.core script only (outside the qgis gui application) but the 'isValid()' function fail to validate the raster, no matter which raster file I try. If I drop the raster tif into the qgis gui it shows all good though. Im running from a Miniconda3 environment on windows using Pyton version 3.7.12 and the qgis package version is 3.18.3. My python code looks like this:

from qgis.core import *
QgsApplication.setPrefixPath("C:/OSGeo4W/bin", True)
qgs = QgsApplication([], False)
qgs.initQgis()
project = QgsProject.instance()
proj_file = 'C:/Data/QGisPrj/File1.qgs'
myLayerFile = 'C:/Data/QGisPrj/myOneBand.tif'
myLayerHandle = QgsRasterLayer(myLayerFile, 'myOneBand', 'gdal')
if not myLayerHandle.isValid():
    print("Layer failed to load!")
else:
    print("Layer loaded!")
    project.addMapLayer(myLayerHandle)

project.write(proj_file) qgs.exitQgis()

And it's returning 'Layer failed to load!'

I'm sure that it's a dead simple fix to it, but have looked in the qgis developer manual as well as seeked on internet but all in vain.

PS: As a side note, if I drop the 'isValid()' function and jump straight to force the 'addMapLayer' function to take the layer, it creates the qgis project file. And multiband RGB tiffs shows up fine when I open the project file in the qgis gui. But for one band tiff's it just shows up in the QGis gui with the envelope grayed and no z values. And when I use the info button and click inside the envelope to see the values at the point where I'm clicking, it shows with no z value no matter where I click. However, when I create a new project from the qgis gui and drop the same one band tiff into it, it shows up fine. So I suspect it must have something to do with the way the layer is configured in the python code. But I'm just not able to see what it can be.

user123442
  • 11
  • 1
  • Have you checked this (https://gis.stackexchange.com/questions/144058/loading-raster-layer-in-a-standalone-pyqgis-script?rq=1) thread? – fastest Sep 12 '22 at 20:22
  • Yes, had already seen that thread. But the 'isValid()' function does not work if I do it like described there either. – user123442 Sep 13 '22 at 08:54

0 Answers0