Hi Olivier, I have been playing with this and I think you should use the source on the layer and not on the data provider. Here is some code (which also modifies the style of the layer) https://github.com/QGEP/customizer/blob/master/customizer.py#L129-L141
I was doing a layer.reload() after changing the source. Hope that helps, Denis Le mar. 25 sept. 2018 à 19:02, Olivier Dalang <[email protected]> a écrit : > 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 > > > > _______________________________________________ > QGIS-Developer mailing list > [email protected] > List info: https://lists.osgeo.org/mailman/listinfo/qgis-developer > Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-developer -- Denis Rouzaud [email protected] <[email protected]> +41 76 370 21 22
_______________________________________________ QGIS-Developer mailing list [email protected] List info: https://lists.osgeo.org/mailman/listinfo/qgis-developer Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-developer
