11

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?

9

You could use something like the following:

from qgis.core import QgsVectorLayer, QgsMapLayerRegistry

vlayer = QgsVectorLayer( "?query=SELECT * FROM road WHERE type = 'Expressway'", "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

| improve this answer | |
  • 1
    I got an error in the Python console: 'QgsMapLayerRegistry' is not defined. The SQL statement works when running in the 'Create a virtual layer' dialog. – eclipsed_by_the_moon Feb 6 '17 at 17:38
  • 1
    Did you include the 'from qgis.core import ...' line? What version are you using? – ndawson Feb 6 '17 at 19:40
  • @eclipsed_by_the_moon - Yes, you're correct. Edited the post to include the necessary imports (thanks to annoymous user for edit). – Joseph Feb 7 '17 at 9:56
  • 1
    @Joseph Thanks for the link provided in your answer! – mgri Feb 7 '17 at 9:59
  • @CyT - Most welcome! Glad it worked =) – Joseph Feb 10 '17 at 9:56
9

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)
| improve this answer | |
  • Given current LTR QGIS version is 3.10, this answer should be the new validated one ! – sigeal Jul 4 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.