4

In very simple beginners terms... how do I refresh the QGIS map canvas (or a specific named layer) as part of a processing script?

I have an extremely simple processing script (below) set up just to make it really easy to change a project variable. One of my map layers has a conditional styling rule set up based on the project variable. After running the script I currently have to manually refresh the canvas (by clicking the refresh button or moving the canvas) to update the map display. For purposes of simple elegance and efficiency I'd like the script to do this automatically.

Please answer in the simplest terms - I'm well out of my depth here.

The script is as follows:

##variable_for_styling=number 0

from qgis.core import *
from PyQt4.QtCore import *

QgsExpressionContextUtils.setProjectVariable('NameOfMyProjectVariable',variable_for_styling)
  • 1
    Wonderful. Yes that works really well. Put your comment as an answer and I'll mark as answered. Thanks - I thought that for someone who knows what they are doing this would be easy. – Rostranimin Mar 10 '17 at 11:08
  • Most welcome, glad it worked! Edited your script slightly as you only need to import a couple of classes. Also, 99% of the time, I don't know what I'm doing :) – Joseph Mar 10 '17 at 11:13
  • 1
    Great - thank you - the answer was just what I needed and at just the right level. – Rostranimin Mar 10 '17 at 11:39
7

You could use iface.mapCanvas().refreshAllLayers() to refresh all layers in the canvas. You also only need to import a couple of classes instead of using import * which imports all classes of a module.

So your script could look like:

##variable_for_styling=number 0

from qgis.core import QgsExpressionContextUtils
from qgis.utils import iface

QgsExpressionContextUtils.setProjectVariable('NameOfMyProjectVariable',variable_for_styling)
iface.mapCanvas().refreshAllLayers()

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.