1

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

4
  • how many layouts are in your manager? Could layout = manager.layouts()[0] be referencing the wrong one?
    – Matt
    Commented Feb 17, 2022 at 23:21
  • I have just seen that you can remove that line, as you reference your layout just a few lines before. And be sure to make the map item before you attempt to change the background colour. I don't see it being made in your code.
    – Matt
    Commented Feb 17, 2022 at 23:23
  • I tried removing layout = manager.layouts()[0] and substituting [0] for [i] to match my loop iteration but neither worked. I'm not getting any errors, the background is just not changing. Is mapItem = item not make the map item?
    – ia200
    Commented Feb 17, 2022 at 23:37
  • In short, no. That was just a general way of finding an existing map item. It was an abstract approach before I saw your code, which you added later. I have adjusted my answer to your specific case. In the code in your question, there is no map item being created, so the loop I initially wrote was just continuing through all the items, and ending up on your page item.
    – Matt
    Commented Feb 18, 2022 at 11:17

2 Answers 2

5

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

4
# these only need to be assigned once, so I moved them out of the loop
project = QgsProject.instance()
manager = project.layoutManager()

# get current extent of map canvas (you may want to use a different extent, this was just for the example)
ext = iface.mapCanvas().extent()

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
    layoutName = " ".join(['Temp Pred Maps', str(i)])
    layouts_list = manager.printLayouts()
    
    # Remove any duplicate layouts
    for j in layouts_list:           # changed i for j to prevent confusion with the i in outer loop
        if j.name() == layoutName:
            manager.removeLayout(j)
    
    # Add add layout to QGIS
    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    layout.setName(layoutName)
    manager.addLayout(layout)
    
    # create map item
    mymap = QgsLayoutItemMap(layout)
    mymap.setRect(20, 20, 20, 20)
    mymap.setCrs(rlayer.crs())
    
    # add layers to map
    ms = QgsMapSettings()
    ms.setLayers([rlayer]) # set layers to be mapped 

    # set the map extent from the map canvas (line 6)
    mymap.setExtent(ext)
    
    # arbitrary map scale, will need adjusting
    mymap.setScale(250000) 
    
    # change background colour (RGBAlpha)
    mymap.setBackgroundColor(QColor(60,255,240,255))
    
    # add map to layout
    layout.addLayoutItem(mymap)

    # adjust the size of map
    mymap.attemptResize(QgsLayoutSize(200, 200, QgsUnitTypes.LayoutMillimeters))
    
    # refresh the layout
    layout.refresh()

enter image description here

1
  • I'm having trouble integrating this into my for loop. I'll add my code above.
    – ia200
    Commented Feb 17, 2022 at 23:11

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.