[QGIS-Developer] Updating a layer's datasource in python

Olivier Dalang olivier.dalang at gmail.com
Tue Sep 25 16:01:52 PDT 2018


Dear List,

As simple as it sounds, I'm struggling with changing the datasource of
layers with python :

layer1 = QgsVectorLayer('/path/to/a.shp')
QgsProject.instance().addMapLayer(layer1)
layer1.dataProvider().setDataSourceUri('/path/to/b.shp')

The layer successfully changes on map redraw. However layer1.source() stays
to the initial layer, so that the change does not persist across saves
(save and reload, and you get a.shp again).

The exact same code with a geopackage doesn't work at all (no changes on
map redraw).

layer1 = QgsVectorLayer('/path/to/db.gpkg|layer=a')
QgsProject.instance().addMapLayer(layer1)
layer1.dataProvider().setDataSourceUri ('/path/to/db.gpkg|layer=b')

There is also an entry in the pyqgis cookbook (here
<https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadlayer.html#id1>,
scroll down) for QgsVectorLayer. The layer1.source() is correctly updated,
but again, it works with shapefiles, but not geopackages. And this is for
vectors only.

layer1.setDataSource('/path/to/b.shp', "b", "ogr")

Am I hitting a bug ? Or did I get confused somewhere ?

As I feel this is a fairly common need, I'd be very grateful if someone
could help me figure out the recommended way to achieve this, for both
vectors or rasters. I'll update the pyqgis cookbook in return :-)

Note that there are workarounds (like replacing with a new layer and
copying styles over or writing directly to the .qgs file, but they are not
straightforward and have limitations).

Thanks !!

Olivier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20180926/7315034c/attachment.html>


More information about the QGIS-Developer mailing list