17

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
35.8k5 gold badges77 silver badges152 bronze badges
asked Feb 6, 2017 at 9:35

2 Answers 2

25

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
35.8k5 gold badges77 silver badges152 bronze badges
answered Mar 20, 2019 at 17:07
1
  • 2
    Given current LTR QGIS version is 3.10, this answer should be the new validated one ! Commented Jul 4, 2020 at 10:04
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
35.8k5 gold badges77 silver badges152 bronze badges
answered Feb 6, 2017 at 10:49
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.