Class: QgsLayout¶
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
While the raw QGraphicsScene API can be used to render the contents of a
QgsLayout to a QPainter, it is recommended to instead use a
QgsLayoutExporter to handle rendering layouts instead.
QgsLayoutExporter automatically takes care of the
intracacies of preparing the layout and paint devices for correct
exports, respecting various user settings such as the layout context
DPI.
Class Hierarchy¶
Base classes¶
Abstract interface for generating an expression context. |
|
Interface for layout objects which support undo/redo commands. |
Subclasses¶
Print layout, a |
Abstract Methods
Creates an expression context relating to the layout's current state. |
Methods
Accepts the specified style entity visitor, causing it to visit all style entities associated with the layout. |
|
Add items from an XML representation to the layout. |
|
Adds an item to the layout. |
|
Adds a multiFrame to the layout. |
|
Clears the layout. |
|
Creates a clone of the layout. |
|
Converts a length measurement from the layout's native units to a specified target unit. |
|
Converts a measurement into the layout's native units. |
|
Returns list of keys stored in custom properties for the layout. |
|
Read a custom property from the layout. |
|
Clears any selected items in the layout. |
|
Returns a reference to the layout's grid settings, which stores settings relating to grid appearance, spacing and offsets. |
|
Creates a new group from a list of layout items and adds the group to the layout. |
|
Returns a reference to the layout's guide collection, which manages page snap guides. |
|
Initializes an empty layout, e.g. by adding a default page to the layout. |
|
Returns a layout item given its id. |
|
Returns the layout item with matching template uuid unique identifier, or |
|
Returns the layout item with matching uuid unique identifier, or |
|
Returns the items model attached to the layout. |
|
Calculates the bounds of all non-gui items in the layout. |
|
Returns the topmost layout item at a specified position. |
|
Load a layout template document. |
|
Lowers an item down the z-order. |
|
Lowers an item down to the bottom of the z-order. |
|
Raises an item up to the top of the z-order. |
|
Returns the layout multiframe with matching uuid unique identifier, or |
|
Returns a list of multi frames contained in the layout. |
|
Returns a pointer to the layout's page collection, which stores and manages page items in the layout. |
|
Returns the bounding box of the items contained on a specified page. |
|
The project associated with the layout. |
|
Raises an item up the z-order. |
|
Returns the map item which will be used to generate corresponding world files when the layout is exported. |
|
Forces the layout, and all items contained within it, to refresh. |
|
Refreshes the layout when global layout related options change. |
|
Remove a custom property from the layout. |
|
Removes an item from the layout. |
|
Removes a multiFrame from the layout (but does not delete it). |
|
Returns a reference to the layout's render context, which stores information relating to the current rendering settings for the layout. |
|
Returns a reference to the layout's report context, which stores information relating to the current reporting context for the layout. |
|
Saves the layout as a template at the given file path. |
|
Returns list of selected layout items. |
|
Set a custom property for the layout. |
|
Sets the map item which will be used to generate corresponding world files when the layout is exported. |
|
Clears any selected items and sets item as the current selection. |
|
Sets the native measurement units for the layout. |
|
Returns a reference to the layout's snapper, which stores handles layout snap grids and lines and snapping points to the nearest matching point. |
|
Returns a pointer to the layout's undo stack, which manages undo/redo states for the layout and it's associated objects. |
|
Ungroups items by removing them from an item group and removing the group from the layout. |
|
Returns the native units for the layout. |
|
Updates the scene bounds of the layout. |
|
Resets the z-values of items based on their position in the internal z order list. |
Virtual Methods
In PyQGIS, only methods marked as virtual can be safely overridden in a Python subclass of QgsLayout. See the FAQ for more details.
Sets the collection's state from a DOM element. |
|
Returns the layout's state encapsulated in a DOM element. |
Signals
Emitted whenever the total number of background tasks running in items from the layout changes. |
|
Emitted when an item was added to the layout. |
|
Emitted when the layout has been refreshed and items should also be refreshed and updated. |
|
Emitted whenever the selected item changes. |
|
Emitted whenever the expression variables stored in the layout have been changed. |
Attributes
- class qgis.core.QgsLayout[source]¶
Bases:
QGraphicsScene,QgsExpressionContextGenerator,QgsLayoutUndoObjectInterface- __init__(project: QgsProject | None)
Construct a new layout linked to the specified
project.If the layout is a “new” layout (as opposed to a layout which will restore a previous state from XML) then
initializeDefaults()should be called on the new layout.- Parameters:
project (Optional[QgsProject])
- class UndoCommand¶
Bases:
int
- UndoLayoutDpi = 0¶
- UndoNone = -1¶
- ZGrid = 9997¶
- ZGuide = 9998¶
- ZItem = 1¶
- ZMouseHandles = 10000¶
- ZPage = 0¶
- ZSmartGuide = 9999¶
- ZSnapIndicator = 10002¶
- class ZValues¶
Bases:
int
- ZViewTool = 10001¶
- accept(self, visitor: QgsStyleEntityVisitorInterface | None) bool[source]¶
Accepts the specified style entity
visitor, causing it to visit all style entities associated with the layout.Returns
Trueif the visitor should continue visiting other objects, orFalseif visiting should be canceled.Added in version 3.10.
- Parameters:
visitor (Optional[QgsStyleEntityVisitorInterface])
- Return type:
bool
- addItemsFromXml(self, parentElement: QDomElement, document: QDomDocument, context: QgsReadWriteContext, position: QPointF | QPoint | None = None, pasteInPlace: bool = False) List[QgsLayoutItem]¶
Add items from an XML representation to the layout. Used for project file reading and pasting items from clipboard.
The
positionargument is optional, and if it is not specified the items will be restored to their original position from the XML serialization. If specified, the items will be positioned such that the top-left bounds of all added items is located at thisposition.The
pasteInPlaceargument determines whether the serialized position should be respected, but remapped to the origin of the page corresponding to the page atposition.A list of the newly added items is returned.
- Parameters:
parentElement (QDomElement)
document (QDomDocument)
context (QgsReadWriteContext)
position (Optional[Union[QPointF, QPoint]] = None)
pasteInPlace (bool = False)
- Return type:
List[QgsLayoutItem]
- addLayoutItem(self, item: QgsLayoutItem | None)[source]¶
Adds an
itemto the layout. This should be called instead of the base classaddItem()method. Ownership of the item is transferred to the layout.- Parameters:
item (Optional[QgsLayoutItem])
- addMultiFrame(self, multiFrame: QgsLayoutMultiFrame | None)[source]¶
Adds a
multiFrameto the layout. The object is owned by the layout untilremoveMultiFrame()is called.See also
See also
- Parameters:
multiFrame (Optional[QgsLayoutMultiFrame])
- signal backgroundTaskCountChanged(total: int)[source]¶
Emitted whenever the
totalnumber of background tasks running in items from the layout changes.Added in version 3.10.
- Parameters:
total (int)
- clear(self)[source]¶
Clears the layout.
Calling this method removes all items and pages from the layout.
- clone(self) QgsLayout | None[source]¶
Creates a clone of the layout. Ownership of the return layout is transferred to the caller.
- Return type:
Optional[QgsLayout]
- convertFromLayoutUnits(self, length: float, unit: Qgis.LayoutUnit) QgsLayoutMeasurement[source]¶
Converts a
lengthmeasurement from the layout’s native units to a specified targetunit.- Return type:
- Returns:
length of measurement in specified units
See also
See also
- Parameters:
length (float)
unit (Qgis.LayoutUnit)
- convertFromLayoutUnits(self, size: QSizeF, unit: Qgis.LayoutUnit) QgsLayoutSize[source]
Converts a
sizefrom the layout’s native units to a specified targetunit.- Return type:
- Returns:
size of measurement in specified units
See also
See also
- Parameters:
size (QSizeF)
unit (Qgis.LayoutUnit)
- convertFromLayoutUnits(self, point: QPointF | QPoint, unit: Qgis.LayoutUnit) QgsLayoutPoint[source]
Converts a
pointfrom the layout’s native units to a specified targetunit.- Return type:
- Returns:
point in specified units
See also
See also
- Parameters:
point (Union[QPointF, QPoint])
unit (Qgis.LayoutUnit)
- convertToLayoutUnits(self, measurement: QgsLayoutMeasurement) float[source]¶
Converts a measurement into the layout’s native units.
- Return type:
float
- Returns:
length of measurement in layout units
See also
See also
- Parameters:
measurement (
QgsLayoutMeasurement)
- convertToLayoutUnits(self, size: QgsLayoutSize) QSizeF[source]
Converts a size into the layout’s native units.
- Return type:
QSizeF
- Returns:
size of measurement in layout units
See also
See also
- Parameters:
size (
QgsLayoutSize)
- convertToLayoutUnits(self, point: QgsLayoutPoint) QPointF[source]
Converts a
pointinto the layout’s native units.- Return type:
QPointF
- Returns:
point in layout units
See also
See also
- Parameters:
point (
QgsLayoutPoint)
- abstract createExpressionContext(self) QgsExpressionContext[source]¶
Creates an expression context relating to the layout’s current state. The context includes scopes for global, project, layout and layout context properties.
- Return type:
- customProperties(self) List[str][source]¶
Returns list of keys stored in custom properties for the layout.
See also
See also
See also
- Return type:
List[str]
- customProperty(self, key: str | None, defaultValue: Any = None) Any[source]¶
Read a custom property from the layout.
- Parameters:
key (Optional[str]) – property key
defaultValue (Any = None) – default value to return if property with matching key does not exist
- Return type:
Any
- Returns:
value of matching property
See also
See also
See also
- deselectAll(self)[source]¶
Clears any selected items in the layout.
Call this method rather than QGraphicsScene.clearSelection, as the latter does not correctly emit signals to allow the layout’s model to update.
- gridSettings(self) QgsLayoutGridSettings¶
Returns a reference to the layout’s grid settings, which stores settings relating to grid appearance, spacing and offsets.
- Return type:
- groupItems(self, items: Iterable[QgsLayoutItem]) QgsLayoutItemGroup | None[source]¶
Creates a new group from a list of layout
itemsand adds the group to the layout. If grouping was not possible,Nonewill be returned.See also
- Parameters:
items (Iterable[QgsLayoutItem])
- Return type:
Optional[QgsLayoutItemGroup]
- guides(self) QgsLayoutGuideCollection¶
Returns a reference to the layout’s guide collection, which manages page snap guides.
- Return type:
- initializeDefaults(self)[source]¶
Initializes an empty layout, e.g. by adding a default page to the layout. This should be called after creating a new layout.
- signal itemAdded(item: QgsLayoutItem)[source]¶
Emitted when an
itemwas added to the layout.Added in version 3.20.
- Parameters:
item (QgsLayoutItem)
- itemById(self, id: str | None) QgsLayoutItem | None[source]¶
Returns a layout item given its
id. Since item IDs are not necessarely unique, this function returns the first matching item found.See also
- Parameters:
id (Optional[str])
- Return type:
Optional[QgsLayoutItem]
- itemByTemplateUuid(self, uuid: str | None) QgsLayoutItem | None[source]¶
Returns the layout item with matching template
uuidunique identifier, orNoneif a matching item could not be found. UnlikeitemByUuid(), this method ONLY checks template UUIDs for a match.Template UUIDs are valid only for items which have been added to an existing layout from a template. In this case the template UUID is the original item UUID at the time the template was created, vs the item’s
uuid()which returns the current instance of the item’s unique identifier.Note that template UUIDs are only available while a layout is being restored from XML.
See also
See also
See also
- Parameters:
uuid (Optional[str])
- Return type:
Optional[QgsLayoutItem]
- itemByUuid(self, uuid: str | None, includeTemplateUuids: bool = False) QgsLayoutItem | None[source]¶
Returns the layout item with matching
uuidunique identifier, orNoneif a matching item could not be found.If
includeTemplateUuidsisTrue, then item’s template UUID will also be tested when trying to match the uuid. This may differ from the item’s UUID for items which have been added to an existing layout from a template. In this case the template UUID returns the original item UUID at the time the template was created, vs the item’suuid()which returns the current instance of the item’s unique identifier. Note that template UUIDs are only available while a layout is being restored from XML.See also
See also
See also
- Parameters:
uuid (Optional[str])
includeTemplateUuids (bool = False)
- Return type:
Optional[QgsLayoutItem]
- itemsModel(self) QgsLayoutModel | None[source]¶
Returns the items model attached to the layout.
- Return type:
Optional[QgsLayoutModel]
- layoutBounds(self, ignorePages: bool = False, margin: float = 0) QRectF[source]¶
Calculates the bounds of all non-gui items in the layout. Ignores snap lines, mouse handles and other cosmetic items.
- Parameters:
ignorePages (bool = False) – set to
Trueto ignore page itemsmargin (float = 0) – optional marginal (in percent, e.g., 0.05 = 5% ) to add around items
- Return type:
QRectF
- Returns:
layout bounds, in layout units.
See also
- layoutItemAt(self, position: QPointF | QPoint, ignoreLocked: bool = False, searchTolerance: float = 0) QgsLayoutItem | None[source]¶
Returns the topmost layout item at a specified
position. Ignores paper items. IfignoreLockedis set toTrueany locked items will be ignored. Since QGIS 3.34 thesearchToleranceparameter was added, which can be used to specify a search tolerance in layout units.- Parameters:
position (Union[QPointF, QPoint])
ignoreLocked (bool = False)
searchTolerance (float = 0)
- Return type:
Optional[QgsLayoutItem]
- layoutItemAt(self, position: QPointF | QPoint, belowItem: QgsLayoutItem | None, ignoreLocked: bool = False, searchTolerance: float = 0) QgsLayoutItem | None[source]
Returns the topmost layout item at a specified
positionwhich is below a specifieditem. Ignores paper items. IfignoreLockedis set toTrueany locked items will be ignored. Since QGIS 3.34 thesearchToleranceparameter was added, which can be used to specify a search tolerance in layout units.- Parameters:
position (Union[QPointF, QPoint])
belowItem (Optional[QgsLayoutItem])
ignoreLocked (bool = False)
searchTolerance (float = 0)
- Return type:
Optional[QgsLayoutItem]
- loadFromTemplate(self, document: QDomDocument, context: QgsReadWriteContext, clearExisting: bool = True)¶
Load a layout template
document.By default this method will clear all items from the existing layout and real all layout settings from the template. Setting
clearExistingtoFalsewill only add new items from the template, without overwriting the existing items or layout settings.If
okis specified, it will be set toTrueif the load was successful.Returns a list of loaded items.
- Parameters:
document (QDomDocument)
context (QgsReadWriteContext)
clearExisting (bool = True) -> (List[QgsLayoutItem])
- lowerItem(self, item: QgsLayoutItem | None, deferUpdate: bool = False) bool[source]¶
Lowers an
itemdown the z-order. ReturnsTrueif the item was successfully lowered.If
deferUpdateisTrue, the scene will not be visibly updated to reflect the new stacking order. This allows multipleraiseItem()calls to be made in sequence without the cost of updating the scene for each one.See also
See also
- Parameters:
item (Optional[QgsLayoutItem])
deferUpdate (bool = False)
- Return type:
bool
- moveItemToBottom(self, item: QgsLayoutItem | None, deferUpdate: bool = False) bool[source]¶
Lowers an
itemdown to the bottom of the z-order. ReturnsTrueif the item was successfully lowered. IfdeferUpdateisTrue, the scene will not be visibly updated to reflect the new stacking order. This allows multipleraiseItem()calls to be made in sequence without the cost of updating the scene for each one.See also
See also
- Parameters:
item (Optional[QgsLayoutItem])
deferUpdate (bool = False)
- Return type:
bool
- moveItemToTop(self, item: QgsLayoutItem | None, deferUpdate: bool = False) bool[source]¶
Raises an
itemup to the top of the z-order. ReturnsTrueif the item was successfully raised.If
deferUpdateisTrue, the scene will not be visibly updated to reflect the new stacking order. This allows multipleraiseItem()calls to be made in sequence without the cost of updating the scene for each one.See also
See also
- Parameters:
item (Optional[QgsLayoutItem])
deferUpdate (bool = False)
- Return type:
bool
- multiFrameByUuid(self, uuid: str | None, includeTemplateUuids: bool = False) QgsLayoutMultiFrame | None[source]¶
Returns the layout multiframe with matching
uuidunique identifier, orNoneif a matching multiframe could not be found.If
includeTemplateUuidsisTrue, then the multiframe’sQgsLayoutMultiFrame.templateUuid()will also be tested when trying to match the uuid. Template UUIDs are valid only for items which have been added to an existing layout from a template. In this case the template UUID is the original item UUID at the time the template was created, vs the item’suuid()which returns the current instance of the item’s unique identifier. Note that template UUIDs are only available while a layout is being restored from XML.See also
- Parameters:
uuid (Optional[str])
includeTemplateUuids (bool = False)
- Return type:
Optional[QgsLayoutMultiFrame]
- multiFrames(self) List[QgsLayoutMultiFrame]¶
Returns a list of multi frames contained in the layout.
See also
See also
- Return type:
List[QgsLayoutMultiFrame]
- pageCollection(self) QgsLayoutPageCollection | None[source]¶
Returns a pointer to the layout’s page collection, which stores and manages page items in the layout.
- Return type:
Optional[QgsLayoutPageCollection]
- pageItemBounds(self, page: int, visibleOnly: bool = False) QRectF[source]¶
Returns the bounding box of the items contained on a specified
page. A page number of 0 represents the first page in the layout.Set
visibleOnlytoTrueto only include visible items.The returned bounds are in layout units.
See also
- Parameters:
page (int)
visibleOnly (bool = False)
- Return type:
QRectF
- project(self) QgsProject | None[source]¶
The project associated with the layout. Used to get access to layers, map themes, relations and various other bits. It is never
None.- Return type:
Optional[QgsProject]
- raiseItem(self, item: QgsLayoutItem | None, deferUpdate: bool = False) bool[source]¶
Raises an
itemup the z-order. ReturnsTrueif the item was successfully raised.If
deferUpdateisTrue, the scene will not be visibly updated to reflect the new stacking order. This allows multipleraiseItem()calls to be made in sequence without the cost of updating the scene for each one.See also
See also
- Parameters:
item (Optional[QgsLayoutItem])
deferUpdate (bool = False)
- Return type:
bool
- virtual readXml(self, layoutElement: QDomElement, document: QDomDocument, context: QgsReadWriteContext) bool[source]¶
Sets the collection’s state from a DOM element.
layoutElementis the DOM node corresponding to the layout.See also
- Parameters:
layoutElement (QDomElement)
document (QDomDocument)
context (QgsReadWriteContext)
- Return type:
bool
- referenceMap(self) QgsLayoutItemMap | None[source]¶
Returns the map item which will be used to generate corresponding world files when the layout is exported. If no map was explicitly set via
setReferenceMap(), the largest map in the layout will be returned (orNoneif there are no maps in the layout).See also
- Return type:
Optional[QgsLayoutItemMap]
- refresh(self)[source]¶
Forces the layout, and all items contained within it, to refresh. For instance, this causes maps to redraw and rebuild cached images, html items to reload their source url, and attribute tables to refresh their contents. Calling this also triggers a recalculation of all data defined attributes within the layout.
See also
- signal refreshed[source]¶
Emitted when the layout has been refreshed and items should also be refreshed and updated.
- removeCustomProperty(self, key: str | None)[source]¶
Remove a custom property from the layout.
- Parameters:
key (Optional[str]) – property key
See also
See also
See also
- removeLayoutItem(self, item: QgsLayoutItem | None)[source]¶
Removes an
itemfrom the layout. This should be called instead of the base classremoveItem()method. The item will also be deleted.- Parameters:
item (Optional[QgsLayoutItem])
- removeMultiFrame(self, multiFrame: QgsLayoutMultiFrame | None)[source]¶
Removes a
multiFramefrom the layout (but does not delete it).See also
See also
- Parameters:
multiFrame (Optional[QgsLayoutMultiFrame])
- renderContext(self) QgsLayoutRenderContext¶
Returns a reference to the layout’s render context, which stores information relating to the current rendering settings for the layout.
- Return type:
- reportContext(self) QgsLayoutReportContext¶
Returns a reference to the layout’s report context, which stores information relating to the current reporting context for the layout.
- Return type:
- saveAsTemplate(self, path: str | None, context: QgsReadWriteContext) bool[source]¶
Saves the layout as a template at the given file
path. ReturnsTrueif save was successful.See also
- Parameters:
path (Optional[str])
context (QgsReadWriteContext)
- Return type:
bool
- signal selectedItemChanged(selected: QgsLayoutItem)[source]¶
Emitted whenever the selected item changes. If
None, no item is selected.- Parameters:
selected (QgsLayoutItem)
- selectedLayoutItems(self, includeLockedItems: bool = True) List[QgsLayoutItem]¶
Returns list of selected layout items.
If
includeLockedItemsis set toTrue, then locked items will also be included in the returned list.- Parameters:
includeLockedItems (bool = True)
- Return type:
List[QgsLayoutItem]
- setCustomProperty(self, key: str | None, value: Any)[source]¶
Set a custom property for the layout.
- Parameters:
key (Optional[str]) – property key. If a property with the same key already exists it will be overwritten.
value (Any) – property value
See also
See also
See also
- setReferenceMap(self, map: QgsLayoutItemMap | None)[source]¶
Sets the
mapitem which will be used to generate corresponding world files when the layout is exported.See also
- Parameters:
map (Optional[QgsLayoutItemMap])
- setSelectedItem(self, item: QgsLayoutItem | None)[source]¶
Clears any selected items and sets
itemas the current selection.- Parameters:
item (Optional[QgsLayoutItem])
- setUnits(self, units: Qgis.LayoutUnit)[source]¶
Sets the native measurement
unitsfor the layout. These also form the default unit for measurements for the layout.See also
See also
- Parameters:
units (Qgis.LayoutUnit)
- snapper(self) QgsLayoutSnapper¶
Returns a reference to the layout’s snapper, which stores handles layout snap grids and lines and snapping points to the nearest matching point.
- Return type:
- undoStack(self) QgsLayoutUndoStack | None[source]¶
Returns a pointer to the layout’s undo stack, which manages undo/redo states for the layout and it’s associated objects.
- Return type:
Optional[QgsLayoutUndoStack]
- ungroupItems(self, group: QgsLayoutItemGroup | None) List[QgsLayoutItem]¶
Ungroups items by removing them from an item
groupand removing the group from the layout. Child items will remain in the layout and will not be deleted.Returns a list of the items removed from the group, or an empty list if ungrouping was not successful.
See also
- Parameters:
group (Optional[QgsLayoutItemGroup])
- Return type:
List[QgsLayoutItem]
- units(self) Qgis.LayoutUnit[source]¶
Returns the native units for the layout.
See also
See also
- Return type:
- updateZValues(self, addUndoCommands: bool = True)[source]¶
Resets the z-values of items based on their position in the internal z order list. This should be called after any stacking changes which deferred z-order updates.
- Parameters:
addUndoCommands (bool = True)
- signal variablesChanged[source]¶
Emitted whenever the expression variables stored in the layout have been changed.
- virtual writeXml(self, document: QDomDocument, context: QgsReadWriteContext) QDomElement[source]¶
Returns the layout’s state encapsulated in a DOM element.
See also
- Parameters:
document (QDomDocument)
context (QgsReadWriteContext)
- Return type:
QDomElement