# getthese projectonly instanceneed to be assigned once, so I moved them out of the loop
pproject = QgsProject.instance()
manager = project.layoutManager()
# get layoutcurrent managerextent of map canvas (you may want to use a different extent, this was just for the example)
mext = piface.layoutManagermapCanvas().extent()
for i in range(1):# getTesting
layout from manager # Load Raster File
layout fn = m"/".layoutsjoin([fldr, targ[i]])[0]
fi = QFileInfo(fn)
# get layout items fname = fi.baseName()
items rlayer = layoutiface.itemsaddRasterLayer(fn, fname)
# iterate through layout itemsrenderer = QgsSingleBandPseudoColorRenderer(rlayer.dataProvider(), 1, shader)
rlayer.setRenderer(renderer)
# Create and findExport mapPrint Layout
layoutName = " ".join(['Temp Pred Maps', str(i)])
layouts_list = manager.printLayouts()
# Remove any duplicate layouts
for itemj in itemslayouts_list: # changed i for j to prevent confusion with the i in outer loop
if isinstancej.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)
breakmymap.setCrs(rlayer.crs())
# add layers to map
mapItem ms = itemQgsMapSettings()
ms.setLayers([rlayer]) # set layers to be mapped
# changeset the backgroundmap colourextent byfrom passingthe anmap RGBcanvas QColor(line object4)
mapItem 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
to apply change
layout.refresh()