16

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?

Taras
  • 32,823
  • 4
  • 66
  • 137
Cy T
  • 697
  • 4
  • 7

2 Answers2

22

For QGIS 3, instead use QgsProject:

from qgis.core import QgsVectorLayer, QgsProject

sql_query = "SELECT * FROM road WHERE type = 'Expressway'" vlayer = QgsVectorLayer(f"?query={sql_query}", "vlayer", "virtual") QgsProject.instance().addMapLayer(vlayer)

Taras
  • 32,823
  • 4
  • 66
  • 137
rwalk
  • 221
  • 2
  • 3
12

For QGIS 2 you could use something like the following:

from qgis.core import QgsVectorLayer, QgsMapLayerRegistry

sql_query = "SELECT * FROM road WHERE type = 'Expressway'" vlayer = QgsVectorLayer(f"?query={sql_query}", "vlayer", "virtual") QgsMapLayerRegistry.instance().addMapLayer(vlayer)

You can find examples on how to use virtual layers through Python from the author's GitHub:

https://github.com/mhugo/qgis_vlayers/blob/master/README.md

Taras
  • 32,823
  • 4
  • 66
  • 137
Joseph
  • 75,746
  • 7
  • 171
  • 282