9

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

7

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
iface.mapCanvas().setCanvasColor(myColor);
iface.mapCanvas().refresh()
2
  • Need to refresh the canvas afterwards with "iface.mapCanvas().refresh()". Then it works.
    – HishivS
    Dec 11, 2015 at 15:52
  • Sorry, should test my code before answering ;) Dec 12, 2015 at 7:40
2

Use setCanvasColor on your map canvas:

iface.mapCanvas().setCanvasColor(QtCore.Qt.red)

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

iface.mapCanvas().setCanvasColor(QtGui.QColor(255,255,0))
1
  • When the project is saved, and opened again later, the colour change doesn't stick.
    – HishivS
    Dec 11, 2015 at 14:37
2

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

# Set the background color to white.
self.canvas.setCanvasColor(Qt.white)
self.canvas.enableAntiAliasing(True)
self.canvas.show()
5
  • As with dmh126's answer, the colour change doesn't stick when then project is saved and opened again later.
    – HishivS
    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
    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
    Dec 11, 2015 at 14:44
  • That answer is refering to layer styles not background colour.
    – HishivS
    Dec 11, 2015 at 14:58
  • It's referring the whole map style.
    – MaryBeth
    Dec 11, 2015 at 15:00

Your Answer

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

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