I often have to reload layers in the layers panel after doing changes in the DB-Manager (add a column, delete a default value, ...). At the moment I use the changeDatasource plugin. Can this also be done using Python?
Asked
Active
Viewed 3,117 times
3 Answers
7
if you have your layer as a variable, simply layer.reload()
You can obtain a list of all layers of the current project from QgsMapLayerRegistry.instance().mapLayers()
If you don’t care about reloading all other layers at the same time, the one-liner
QgsMapLayerRegistry.instance().reloadAllLayers()
does the job, too.
References:
christoph
- 573
- 2
- 8
5
QgsProject.instance().reloadAllLayers() worked for me on QGIS 3.10.
Kadir Şahbaz
- 76,800
- 56
- 247
- 389
Romário Carvalho Neto
- 69
- 1
- 2
-
Welcome to GIS SE! As a new user please take the [tour]. A good answer should include details about how to use your suggestion and info about what it does. Please [edit] your answer to add additional info. – Midavalo Apr 09 '21 at 15:32
4
I've read several answers for this specific question; none of them seems to work. The only effective solution I could find is:
layer.setDataSource( layer.source(), layer.name(), layer.providerType() )
Tested in QGIS v2.14.8.
Germán Carrillo
- 36,307
- 5
- 123
- 178
QgsMapLayerRegistry.instance().reloadAllLayers()in the Python console returns an error:Traceback (most recent call last): File "/usr/lib/python3.5/code.py", line 91, in runcode exec(code, self.locals) File "<input>", line 1, in <module> NameError: name 'QgsMapLayerRegistry' is not defined– eclipsed_by_the_moon Jan 28 '17 at 20:28layer = qgis.utils.iface.mapCanvas().currentLayer() layer.reload()doesn't work. – eclipsed_by_the_moon Jan 28 '17 at 20:39iface.mapCanvas().currentLayer().reload()should work – checking it here in a moment – christoph Jan 29 '17 at 17:13QgsMapCanvasrefers to to the user interface,QgsMapLayerRegistryto the QGIS project)
– christoph Jan 29 '17 at 21:34QgsMapLayerRegistry.instance().reloadAllLayers()works as expected, too.layer.dataProvider().setDataSourceUri(layer.dataProvider().dataSourceUri())– christoph Jan 31 '17 at 17:23