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?

Joseph
  • 75,746
  • 7
  • 171
  • 282
Martin
  • 2,908
  • 4
  • 22
  • 44

2 Answers2

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()
Martin
  • 2,908
  • 4
  • 22
  • 44
Joseph
  • 75,746
  • 7
  • 171
  • 282
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.

Lilium
  • 1,057
  • 1
  • 6
  • 17
mr3
  • 121
  • 4
  • 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 02 '18 at 02:16