- Home
- Geospatialblog
- PyQGIS for layout
PyQGIS for layout
Published Date: Sept. 5, 2024, 5:07 a.m. || Abin Prajapti 342 views

PyQGIS provides a powerful way to automate map production and manage map layouts programmatically. The QgsLayout and related classes in PyQGIS allow you to create, customize, and export layouts for maps, reports, and other geospatial visualizations.
Here's a quick guide on how to create a map layout using PyQGIS:
Steps to Create a Map Layout in PyQGIS
-
Create a Layout Manager and a Layout:
- Initialize a layout manager from the project.
- Create a new QgsLayout object to hold the layout.
-
Add a Map Item to the Layout:
- Create a QgsLayoutItemMap object and set its extent.
- Add the map item to the layout.
-
Customize the Layout:
- Add other elements such as labels, legends, scale bars, and north arrows.
- Customize the layout size, position, and properties of these elements.
-
Export the Layout:
- Export the layout to various formats such as PDF, PNG, or SVG.
Sample Code to Create a Map Layout
Here's an example that demonstrates how to create a basic map layout in PyQGIS:
from qgis.core import (
QgsProject,
QgsPrintLayout,
QgsLayoutItemMap,
QgsLayoutItemLegend,
QgsLayoutItemScaleBar,
QgsLayoutItemLabel,
QgsUnitTypes,
QgsLayoutExporter,
QgsLayoutSize
)
from qgis.PyQt.QtCore import QRectF
# Access the current QGIS project
project = QgsProject.instance()
# Create a new print layout object
layout = QgsPrintLayout(project)
layout.initializeDefaults()
layout.setName("My Layout")
# Add the layout to the layout manager
manager = project.layoutManager()
manager.addLayout(layout)
# Create a map item
map_item = QgsLayoutItemMap(layout)
map_item.setRect(20, 20, 200, 100) # Set the rectangle size and position
map_item.setExtent(project.mapLayersByName('your_layer_name')[0].extent()) # Set map extent to a layer's extent
# Set scale and position for map item
map_item.attemptSetSceneRect(QRectF(5, 5, 200, 100)) # Set position in layout
map_item.setScale(100000) # Set map scale
# Add the map item to the layout
layout.addLayoutItem(map_item)
# Add a label item
label_item = QgsLayoutItemLabel(layout)
label_item.setText("My Map Title")
label_item.setFont(QFont("Arial", 18))
label_item.adjustSizeToText()
label_item.setItemPosition(10, 10) # Position in layout
layout.addLayoutItem(label_item)
# Add a scale bar
scale_bar = QgsLayoutItemScaleBar(layout)
scale_bar.setStyle('Single Box')
scale_bar.setUnits(QgsUnitTypes.DistanceMeters)
scale_bar.setNumberOfSegments(4)
scale_bar.setHeight(5)
scale_bar.setItemPosition(5, 110)
layout.addLayoutItem(scale_bar)
# Add a legend
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.setLinkedMap(map_item)
legend.setItemPosition(210, 20)
layout.addLayoutItem(legend)
# Export layout to PDF
exporter = QgsLayoutExporter(layout)
exporter.exportToPdf('/path/to/output/my_map_layout.pdf', QgsLayoutExporter.PdfExportSettings())
print("Layout created and exported successfully!")