PyQGIS Virtual Layer – Creating Virtual Layer with PyQGIS

pyqgisvirtual-layer

Is it possible to create a Virtual Layer through a Python script? For example, I have a layer "road", and I would like to perform the SQL query

SELECT *
FROM road
WHERE type = 'Expressway'

Will this be possible? Is there any example I can refer to?

Best Answer

For QGIS 3, instead use QgsProject:

from qgis.core import QgsVectorLayer, QgsProject
vlayer = QgsVectorLayer( "?query=SELECT * FROM road WHERE type = 'Expressway'", "vlayer", "virtual" )
QgsProject.instance().addMapLayer(vlayer)
Related Question