# 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 4)
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()
Matt
- 17.9k
- 4
- 23
- 59