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

Nyall Dawson nyall.dawson at gmail.com
Tue Sep 25 17:09:41 PDT 2018

On Wed, 26 Sep 2018 at 09:02, Olivier Dalang <olivier.dalang at gmail.com> wrote:
> 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')

This code won't work correctly -- you shouldn't be changing the data
source of the layer's provider, but rather set the layer's data source
and let it handle the required changes to the provider.

> There is also an entry in the pyqgis cookbook (here, 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.

This should work for geopackage (as well as shp). Can you share your code?

And yes, there's unfortunately no equivalent for rasters yet.


More information about the QGIS-Developer mailing list