2

I am trying to load an .ecw file with pyqgis on a pc. Usin version 2.14 of QGIS. I tried the code i could find in the cookbook about loading and rendering raster from it I interpred this code:

from qgis.core import QgsRasterLayer
import os
os.chdir(r'C:\some\path')
file = 'FooBar.ecw'
fileInfo = QFileInfo(file)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(file, baseName)
if not rlayer.isValid():
    print "Layer failed to load again!"
else:
    print rlayer.renderer()
    print rlayer.renderer().type()
    if hasattr(rlayer, "setCacheImage"):
        rlayer.setCacheImage(None)
    rlayer.triggerRepaint()

I will get a dialog window where I get to define the projection for the raster. But th file will not draw. The file is fully functionall to load normally. How can I make the raster draw with pyqgis?

1
  • Try using qgis.utils.iface.addRasterLayer("/path/to/raster", "any_name") to load the raster to the map registry. I think what you are doing is just accessing the raster but not loading it.
    – Joseph
    May 18, 2017 at 15:19

1 Answer 1

2

Almost done! As @Joseph correctly suggested, you only need to load the raster to the map registry.

There was also a missing import in the code.

The following code should work for you:

from qgis.core import QgsRasterLayer
from PyQt4.QtCore import QFileInfo
import os
os.chdir(r'C:\some\path')
file = 'FooBar.ecw'
fileInfo = QFileInfo(file)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(file, baseName)
if not rlayer.isValid():
    print "Layer failed to load again!"
else:
    print rlayer.renderer()
    print rlayer.renderer().type()
    if hasattr(rlayer, "setCacheImage"):
        rlayer.setCacheImage(None)
    rlayer.triggerRepaint()

# Add the layer to the Layers panel
QgsMapLayerRegistry.instance().addMapLayer(rlayer)
0

Your Answer

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

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