PyQGIS – Setting Background Color in Print Layout from Python Console in QGIS

pyqgisqgis-3

I would like to change the background color in my print layout from the Python console in QGIS. I can see some of the background color (currently white) near the corners of my layout and I would like to change this color.


I tried adding the suggested code to my for loop but was still getting the white background. Here is my code (see the # Change background color section at the end):

for i in range(1):# Testing
    
    # Load Raster File
    fn = "/".join([fldr, targ[i]])
    fi = QFileInfo(fn)
    fname = fi.baseName()
    rlayer = iface.addRasterLayer(fn, fname)
    
    renderer = QgsSingleBandPseudoColorRenderer(rlayer.dataProvider(), 1, shader)
    rlayer.setRenderer(renderer)
    
    # Create and Export Print Layout
    # Identify Layer for Map
    layers = QgsProject.instance().mapLayersByName(fname)
    layer = layers[0]
    project = QgsProject.instance()
    manager = project.layoutManager()
    layoutName = " ".join(['Temp Pred Maps', str(i)])
    layouts_list = manager.printLayouts()
    
    # Remove any duplicate layouts
    for i in layouts_list:
        if i.name() == layoutName:
            manager.removeLayout(i)
    
    # Add add layout to QGIS
    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    layout.setName(layoutName)
    manager.addLayout(layout)
    
    # Change background color
    layout = manager.layouts()[0]
    items = layout.items()
    for item in items:
        if isinstance(item, QgsLayoutItemMap):
            break
        
    mapItem = item
    mapItem.setBackgroundColor(QColor(60,255,240))
    layout.refresh()

enter image description here

Best Answer

If you want to have the same map background color as the page, you can disable background color for the map item.

mapItem.setBackgroundEnabled(False)

enter image description here

Related Question