5

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?

3 Answers 3

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:

8
  • Running 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 Jan 28, 2017 at 20:28
  • layer = qgis.utils.iface.mapCanvas().currentLayer() layer.reload() doesn't work. Jan 28, 2017 at 20:39
  • in the Python console iface.mapCanvas().currentLayer().reload() should work – checking it here in a moment
    – christoph
    Jan 29, 2017 at 17:13
  • It works as long as a layer is selected in the layer list (QgsMapCanvas refers to to the user interface, QgsMapLayerRegistry to the QGIS project) QgsMapLayerRegistry.instance().reloadAllLayers() works as expected, too.
    – christoph
    Jan 29, 2017 at 21:34
  • Perhaps it's a QGIS 2.x/3.x issue. I'll test this in QGIS 2.18 tomorrow. Jan 30, 2017 at 9:27
5

QgsProject.instance().reloadAllLayers() worked for me on QGIS 3.10.

1
  • 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 9, 2021 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.