[QGIS-Developer] setDataSourceUri() not working

Raymond Nijssen r.nijssen at terglobo.nl
Wed Dec 7 07:39:50 PST 2022


Hi Devs,

I'm trying to change the dataSourceUri of an existing layer, but can't 
get it working. The reason is that my layer should be connected to 
another view in the same database, because the db should do some 
calculations for my plugin.

I created a test script for a simple polygon layer in a gpkg, which I 
attached to this email. The layer "polygons" and both views are all 
working correctly if you just drag and drop the gpkg in QGIS.

Open the polygons layer and select it. Then run:


layer = iface.activeLayer()
provider = layer.dataProvider()

ds = provider.dataSourceUri()
print(ds)

fn = ds.split('|layername=')[0]
new_ds = fn + '|layername=highest_3_view'
print(new_ds)

provider.setDataSourceUri(new_ds)




The first run displays 2 different dataSourceUris:
path/to/test_views.gpkg|layername=polygons
path/to/test_views.gpkg|layername=highest_3_view

The second run displays 2x the same dataSourceUris:
path/to/test_views.gpkg|layername=polygons
path/to/test_views.gpkg|layername=highest_3_view

So the string has been changed. But my layer properties still point to 
path/to/test_views.gpkg|layername=polygons

and the features displayed are all 5 from the polygons layer. (The views 
have only 3 features)



Should i do something after setting the new provider? I've been trying 
many things, including:
* provider.reloadData()
* layer.setDataProvider(dataprovider)
* refreshing/redrawing the layer


Hope anyone can help!
Raymond
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test_views.gpkg
Type: application/geopackage+sqlite3
Size: 98304 bytes
Desc: not available
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20221207/9281402b/attachment-0001.bin>


More information about the QGIS-Developer mailing list