QGIS PyQGIS – Making Backgrounds White for QgsLayoutItems in QGIS Python Console

pyqgispyqgis-3pythonqgis

I would like the background of my label and scale bar items to be white rather than transparent.

enter image description here

I am using Python in QGIS. My code is below. See the # Add Scalebar and # Add Title sections towards the end. Note that this code is within a loop because I will be generating and exporting a series of maps with the same layout. I generate the render colors in code outside the loop but don't include it here because the code is already long.

I tried this based on another post but it didn't work for me.

    scalebar = super(QgsLayoutItem, scalebar)
    scalebar.setBrush(QColor(255,255,255))
for i in range(0,len(targ)):
    
    # 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)
    
    # SET PAGE SIZE HERE
    #*** HOW TO SET PAGE SIZE? ***
    page = QgsLayoutItemPage(layout)
    page_size = QgsLayoutSize(200, 200, QgsUnitTypes.LayoutMillimeters)
    #page.QgsPageSize(page_size.size) # Error
    page.attemptResize(page_size) # Does Nothing???
    #layout.addLayoutItem(page) # Adds second page
    #layout.removeLayoutItem(layout)
    
    # Create map item in the layout
    map = QgsLayoutItemMap(layout)
    map.setRect(20,20,20,20)
    
    # set the map extent
    ms = QgsMapSettings()
    ms.setLayers([layer]) # set layers to be mapped
    rect = QgsRectangle(can_ext)
    rect.scale(1)
    ms.setExtent(rect)
    map.setExtent(rect)
    layout.addLayoutItem(map)
    map.attemptMove(QgsLayoutPoint(0, 0, QgsUnitTypes.LayoutMillimeters))
    map.attemptResize(QgsLayoutSize(200, 200, QgsUnitTypes.LayoutMillimeters))
    
    # Create Legend *** NEED TO GET TEMP VALUES IN LEGENED ***
    legend = QgsLayoutItemLegend(layout)
    legend.setTitle("")
    layer.setName("Temperature (C)") # change layer name for legend
    layerTree = QgsLayerTree()
    layerTree.addLayer(layer)
    legend.model().setRootGroup(layerTree)
    legend.setStyleFont(QgsLegendStyle.Subgroup, QFont('Arial', 20))
    layout.addLayoutItem(legend)
    legend.attemptMove(QgsLayoutPoint(140, 0, QgsUnitTypes.LayoutMillimeters))
    # legend.update()
    # layout.removeLayoutItem(legend)
    
    # Add Scalebar
    scalebar = QgsLayoutItemScaleBar(layout)
    scalebar.setStyle('Single Box')
    scalebar.setUnits(QgsUnitTypes.DistanceMeters)
    scalebar.setNumberOfSegments(2)
    scalebar.setNumberOfSegmentsLeft(0)
    scalebar.setUnitsPerSegment(100)
    scalebar.setLinkedMap(map)
    scalebar.setUnitLabel('m')
    scalebar.setFont(QFont('Arial', 20))
    scalebar.update()
    layout.addLayoutItem(scalebar)
    scalebar.attemptMove(QgsLayoutPoint(120, 193, QgsUnitTypes.LayoutMillimeters))
    
    
    scalebar = super(QgsLayoutItem, scalebar)
    scalebar.setBrush(QColor(255,255,255)) # This isn't working
    
    # Add Title
    #   Generate Titles
    date_time = re.split("T[1/2/3] ", fname)[1]
    date_only = re.split(" ", date_time)[0]
    time_only = re.split(" ", date_time)[1]
    time_only = re.split("-", time_only)[0]+":"+re.split("-", time_only)[1]
    
    #    Date Title
    title = QgsLayoutItemLabel(layout)
    title.setText(date_only)
    title.setFont(QFont('Arial', 30))
    title.adjustSizeToText()
    title.setBackgroundColor(QColor(255, 255, 255, 255)) # Not working???
    layout. addLayoutItem(title)
    title.attemptMove(QgsLayoutPoint(3, 3, QgsUnitTypes.LayoutMillimeters))
    # title.update()
    # layout.removeLayoutItem(title2)
    
    #   Time Title
    title2 = QgsLayoutItemLabel(layout)
    title2.setText(time_only)
    title2.setFont(QFont('Arial', 30))
    title2.adjustSizeToText()
    title2.setBackgroundColor(QColor(255, 255, 255, 255)) # Not working???
    layout. addLayoutItem(title2)
    title2.attemptMove(QgsLayoutPoint(3, 20, QgsUnitTypes.LayoutMillimeters))
    
    # Export Map Layout
    # layout = manager.layoutByName(layoutName)
    exporter = QgsLayoutExporter(layout)
    fn = export_folder + "/" + fname + ".jpg" # file export directory and filename
    exporter.exportToImage(fn, QgsLayoutExporter.ImageExportSettings())

Best Answer

You need to enable the background (it is white by default).

title.setBackgroundEnabled(True)

enter image description here