Tuesday 23 October 2018

Refreshing QGIS layers panel after update in python



How can I refresh the Layers Panel in QGIS through python?


In my code I have loop and within line to update visibility of some layer in the legend:


self.iface.legendInterface().setLayerVisible( layer, True )

At the beginning I thought it should do that that automatically. But it doesn't. Very interesting thing for me is that if I have open Python Console and print something after that line the Layers Panel gets updated. If the Python Console is closed nothing happens.


My intention is to build plugin witch loop through layers in selected group and for every layer turns it on (the rest in group turn off) and export composer. The whole problem is that after switching visibility of layers the Layers Panel won't update automatically and so also the composer is not updated and gets exported without any change in the layers visibility. Just accidentally I have found out that if I open Python Console and with every loop print out something not only Python Console gets updated but for some reason also Layers Panel and so Composer and so the export works as needed. But I feel it would be stupid to say if you want my plugin to work correctly you need to open python console... There must be some trigger or something to force Layers Panel to update. What is it? :)



Answer



This answer might be related to many other problems too. Thanks to the Maps Printer plugin I have figured out how to ensure things are going to be refreshed (processed) as needed:


from PyQt4.QtCore import QCoreApplication


# This line is going to update (process) everything which might wait in cue like refreshing the layers in map in print composer
QCoreApplication.processEvents()

My big thanks to the developer of Maps Printer plugin (Harrissou Sant-anna / CAUE du Maine-et-Loire) who's code contains these lines which helped me to figure this out and Germán Carrillo who pointed me in the right direction.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...