Sunday, 22 January 2017

python - How to automatically reload raster layers if source is changed in QGIS?


How to automatically reloaded raster layer if source is changed? (The path is the same but inside source file are changes)


I use:


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

but layer not refresh.


# # #


The maps are repainting but there are still the same image (source file is changed on disc)


I use:


  layers = qgis.utils.iface.legendInterface().layers()

for layer in layers:
layer.triggerRepaint()

Answer



I suppose your question does not include change detection, as your sample only concerns QgsMapCanvas.refresh()


Instead you have to call QgsRasterLayer.triggerRepaint()


If your layer is called myLayer:


myLayer.setCacheImage( None )
myLayer.triggerRepaint()

The same method exists for vector layers as well.



For low overhead file change notification I'd propose looking into Qt's QFileSystemWatcher, which makes use of inotify on linux and similar techniques on other platforms.


from PyQt4.QtCore import QFileSystemWatcher

def refreshLayer():
myLayer.setCacheImage( None )
myLayer.triggerRepaint()

watcher = QFileSystemWatcher()
watcher.addPath( '/path/to/your/raster' )
watcher.fileChanged.connect( refreshLayer )


Of course this can be combined with an MD5 check as proposed by nickves or a modification time check with os.stat (Nathan W proposal).


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...