I would like to change the background colour of a QGIS project using python.

I can change the colour using the GUI via the Project Properties dialog: Project Properties dialog

However, I cannot find the equivalent setting in the Python API. I have tried setting the canvas colour using iface.mapCanvas().setCanvasColor(), but the colour change does not stay after the project file is saved, and reopened again layer.

3 Answers 3


To change the color of a project permanently, write it as project property:

myColor = Qt.white;

# Write it to the project (will still need to be saved!)
QgsProject.instance().writeEntry("Gui", "/CanvasColorRedPart", myColor.red())
QgsProject.instance().writeEntry("Gui", "/CanvasColorGreenPart", myColor.green())
QgsProject.instance().writeEntry("Gui", "/CanvasColorBluePart", myColor.blue())

# And apply for the current session
  • Need to refresh the canvas afterwards with "iface.mapCanvas().refresh()". Then it works.
    – HishivS
    Commented Dec 11, 2015 at 15:52
  • Sorry, should test my code before answering ;) Commented Dec 12, 2015 at 7:40

Use setCanvasColor on your map canvas:


Or you can define color with QColor(R,G,B):

  • When the project is saved, and opened again later, the colour change doesn't stick.
    – HishivS
    Commented Dec 11, 2015 at 14:37

Here is a link to another question where Python code for QGIS has code for background color data.

# Set the background color to white.
  • As with dmh126's answer, the colour change doesn't stick when then project is saved and opened again later.
    – HishivS
    Commented Dec 11, 2015 at 14:38
  • As quoted from the link posted in my answer: This is because without having a default style set QGIS doesn't know how to display the layer and just picks a random fill/line/point colour. If you are loading it in QGIS and getting the same colour changes are you have saved a default style for the layer and QGIS is loading that.
    – MaryBeth
    Commented Dec 11, 2015 at 14:42
  • Also, if there are things that you have tried and haven't worked, it's helpful to edit your question to reflect those. Not everyone will read through all of the answers and comments to get the details that need to be outlined in your question.
    – MaryBeth
    Commented Dec 11, 2015 at 14:44
  • That answer is refering to layer styles not background colour.
    – HishivS
    Commented Dec 11, 2015 at 14:58
  • It's referring the whole map style.
    – MaryBeth
    Commented Dec 11, 2015 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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