Skip to main content
2 of 2
added 14 characters in body; edited title
Taras
  • 34.1k
  • 4
  • 73
  • 148

Creating virtual raster as layer to map with PyQGIS

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.