3

I would like to load a virtual raster as a layer into my map. I have tried changing the data source attribute to 1 (relative), as described here: Loading virtual vector layer in QGIS

What do I need to change for the raster? I have tried both QgsRasterLayer and QgsVectorLayer.

import os
from osgeo import gdal

vrt_options = gdal.BuildVRTOptions(resampleAlg='nearestNeighbor', addAlpha=False)
gdal.BuildVRT(r'D:\QGIS\ni25.vrt', [r'D:\QGIS\dtk25.tif'], options=vrt_options)

vrt_path = r'D:\QGIS\ni25.vrt'
Layer = QgsRasterLayer(vrt_path, "ni25_vrt", "ogr")

if not Layer.isValid():
    print("Layer failed to load!")

QgsProject.instance().addMapLayer(Layer)

The layer is added but nothing shows up on the map and there is a warning saying that the layer data source could not be found. When I drag the vrt into the layers window, it works.

1
  • 2
    Try passing 'gdal' instead of 'ogr' for the provider argument. 'ogr' is for vector layers.
    – Ben W
    Commented May 2, 2023 at 13:03

2 Answers 2

3

Of course "Explicit is better than implicit" as stated in The Zen of Python.

However, QGIS is smart and one can also create a QgsRasterLayer without specifying the providerType, e.g.:

my_raster_layer = QgsRasterLayer("/path/to/file.tif", "my layer")

In your case it will be:

Layer = QgsRasterLayer(vrt_path, "ni25_vrt")

See QGIS Python API | Class: QgsRasterLayer for more details.

2

As @BenW has pointed out, ogr has to be changed to gdal:

Layer = QgsRasterLayer(vrt_path, "ni25_vrt", "gdal")

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.