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
iface.mapCanvas().setCanvasColor(myColor);
iface.mapCanvas().refresh()
-
Need to refresh the canvas afterwards with "iface.mapCanvas().refresh()". Then it works.HishivS– HishivS2015年12月11日 15:52:26 +00:00Commented Dec 11, 2015 at 15:52
-
Sorry, should test my code before answering ;)Matthias Kuhn– Matthias Kuhn2015年12月12日 07:40:38 +00:00Commented Dec 12, 2015 at 7:40
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))
-
When the project is saved, and opened again later, the colour change doesn't stick.HishivS– HishivS2015年12月11日 14:37:14 +00:00Commented 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. self.canvas.setCanvasColor(Qt.white) self.canvas.enableAntiAliasing(True) self.canvas.show()
-
As with dmh126's answer, the colour change doesn't stick when then project is saved and opened again later.HishivS– HishivS2015年12月11日 14:38:08 +00:00Commented 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– MaryBeth2015年12月11日 14:42:56 +00:00Commented 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– MaryBeth2015年12月11日 14:44:11 +00:00Commented Dec 11, 2015 at 14:44
-
That answer is refering to layer styles not background colour.HishivS– HishivS2015年12月11日 14:58:28 +00:00Commented Dec 11, 2015 at 14:58
-
It's referring the whole map style.MaryBeth– MaryBeth2015年12月11日 15:00:54 +00:00Commented Dec 11, 2015 at 15:00