It should be enough to update the layer data source with an appropriate URI. See the following examples involving 2 layers from Natural Earth (airports and countries) and 2 different queries for each layer.
pathAirports = u'/docs/geodata/world/ne_10m_airports.shp'
pathCountries = u'/docs/geodata/world/ne_10m_admin_0_countries.shp'
queryAirports="SELECT * FROM airports"
queryAirports2="SELECT * FROM airports WHERE type='major'"
queryCountries="SELECT * FROM countries"
queryCountries2="SELECT * FROM countries WHERE SUBREGION='South America'"
layer = QgsVectorLayer(
"?layer=ogr:{}:airports&query={}".format( pathAirports, queryAirports ),
"Airports",
"virtual" )
QgsMapLayerRegistry.instance().addMapLayer( layer )
layer.setDataSource(
"?layer=ogr:{}:airports&query={}".format( pathAirports, queryAirports2 ),
"Some Airports",
"virtual" )
layer.setDataSource(
"?layer=ogr:{}:countries&query={}".format( pathCountries, queryCountries ),
"Countries",
"virtual" )
layer.setDataSource(
"?layer=ogr:{}:countries&query={}".format( pathCountries, queryCountries2 ),
"Some countries",
"virtual" )
However, there seems to be a bug with Virtual Layers that doesn't allow you to select features properly using canvas tools. For instance, after running the last line above, I cannot select Brasil
using the select tool (it keeps selecting Argentina
!). I've confirmed this on QGIS v2.14.8 (GNU/Linux), QGIS 2.16.3 (Windows 7), and a recent QGIS build v2.99 (GNU/Linux). This is not a bug due to the PyQGIS code above, in fact, creating the virtual layer from QGIS GUI (either from DB Manager
or Manage Layers Toolbar
) I get the same result. Can you confirm such behavior?
"layer1"
and"layer2"
) and one virtual layer, if the user selects"layer1"
from the plugin, the virtual layer will be updated to be exactly like"layer1"
. And vice-versa if the user selects"layer2"
. – Joseph Nov 17 '16 at 13:52