10

Before I used the function

qgis.utils.iface.mapCanvas().refresh()

to reload the map canvas after for example a layer color was changed from a plugin. But this is not working with QGIS 2.6 for me. Do I have to use another function to refresh the map canvas or is this a bug?

2 Answers 2

14

It may very well be a bug as I also cannot get the canvas to refresh. You can try the following as a workaround:

myLayer.triggerRepaint()

To refresh all layers following function can be used:

def refresh_layers(self):
    for layer in qgis.utils.iface.mapCanvas().layers():
        layer.triggerRepaint()
4
  • 1
    Thank you! This is working. I've added a function to your answer for refreshing all layers (more or less) at once ;)
    – Martin
    Feb 23, 2015 at 12:43
  • 1
    Brilliant Martin! I was trying to test something similar but you got it! Many thanks for that =)
    – Joseph
    Feb 23, 2015 at 12:44
  • 1
    In the console: def refresh_layers(): Apr 26, 2017 at 14:38
  • 1
    @Vesanto - Yes, you are correct in that you don't need self if typing it in the console :)
    – Joseph
    Apr 26, 2017 at 14:47
2

With canvas caching in the mix (python cookbook, note at the end of the 'Modifying Vector Layers' section), I have to do the following to get a dependable refresh after an edit (in my case from within plugin code in QGIS 2.14):

cachingEnabled = self.iface.mapCanvas().isCachingEnabled()

for layer in self.iface.mapCanvas().layers():
    if cachingEnabled:
        layer.setCacheImage(None)
    layer.triggerRepaint()

self.iface.mapCanvas().refresh()

That is, I always call triggerRepaint() on all layers and then call the mapCanvas's refresh() just to be safe. If caching is enabled, I also reset each layer's cache image before triggering that layer's repaint. I don't know if all of this is required, but I do know it appears to work consistently. The API warns that both QgsMapLayer.setCacheImage() and QgsMapLayer.clearCacheImage() are deprecated, but nothing in the documentation or code mentions what alternative is planned.


Side note: I'm still seeing a refresh bug. If I open the python console before a plugin's first layer edit (in the current project at least), then no matter what the plugin does the map won't refresh. If instead I at least wait to open the console until after the first edit then everything seems to be fine. Just something to be aware of if you're trying to get refreshes to work.

1
  • Also, the triggerRepaint() logic came from the advice in Joseph's answer above...I would have tried to just add this as a comment to that answer if my rep had allowed it.
    – mr3
    Mar 2, 2018 at 2:16

Your Answer

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

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