0

I am using a database view as a source to draw a line over a map in QGIS 2.18.12. This view contains just one registration and it changes from time to time. I would like to draw the line automatically when the view changes. Is it possible to do this from a Python script? For the moment my solution is to reload the whole project, but it is not as fine as I expected because I want to refresh just the line not all layers.

The code I use now is:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from qgis.utils import iface
from PyQt4.QtCore import QTimer

timer = QTimer()

timer.setInterval(10000)
QObject.connect(timer, 
SIGNAL("timeout()"),qgis.utils.iface.mapCanvas().refreshAllLayers)
timer.start()
  • 1
    Does this answer help? gis.stackexchange.com/a/136405/25417 You could add a check for each layer in the loop, and only refresh if it matches the layer you want to update. – Richard Law Nov 27 '18 at 8:18
  • Hmm. It is not OK. I would like to reload only the PostGIS layer (the line), but thank you. – Friedrich Maar Nov 27 '18 at 8:54
  • 1
    If you know the name of the layer, then maybe you could adapt that answer? e.g. for layer in qgis.utils.iface.mapCanvas().layers(): then inspect layer to see if it matches your criteria, then layer.triggerRepaint()? – Richard Law Nov 27 '18 at 10:35
  • Ok! I know my layer name and I have already changed qgis.utils.iface.mapCanvas().refreshAllLayers with layerName.triggerRepaint. I am having an error ---- NameError: name 'layerName' is not defined. This is my problem – Friedrich Maar Nov 27 '18 at 12:20
  • It looks like your answer is OK for my need, but with few adjustments. I am new in Python and QGIS technology. Thank you! Have a nice week! – Friedrich Maar Nov 27 '18 at 16:39
2

Something like this would be better:

# import only the things you need
from PyQt4.QtCore import QTimer

layer_name = 'layer' # Define the name of your layer here (change 'layer' to your layer name) 

def refresh():
    """refresh the layer with name 'layer_name'"""
    # get your layer by name
    layer = QgsMapLayerRegistry.instance().mapLayersByName(layer_name)[0]
    # refresh your layer
    layer.triggerRepaint()

timer = QTimer()
timer.setInterval(10000) # 10 seconds
timer.timeout.connect(refresh) # Better to use the new signal/slot syntax
timer.start()

You can run this code in a Qgis2.X python console

Closing QGIS will make all that stops, you may want to add the possibility to stop this script while QGIS is running, but it's another topic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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