Class: QgsLayerTreeModel

A model representing the layer tree, including layers and groups of layers.

The model can be used in any QTreeView, it is however recommended to use it with QgsLayerTreeView which brings additional functionality specific to layer tree handling.

The model listens to the changes in the layer tree and signals the changes as appropriate, so that any view that uses the model is updated accordingly.

Behavior of the model can be customized with flags. For example, whether to show legend or whether to allow changes to the layer tree.

See also

QgsLayerTreeView

Class Hierarchy

Inheritance diagram of qgis.core.QgsLayerTreeModel

Base classes

QAbstractItemModel

QObject

Subclasses

QgsLegendModel

Item model implementation based on layer tree model for layout legend.

class qgis.core.QgsLayerTreeModel[source]

Bases: QAbstractItemModel

__init__(rootNode: QgsLayerTree | None, parent: QObject | None = None)

Construct a new tree model with given layer tree (root node must not be None). The root node is not transferred by the model.

Parameters:
  • rootNode (Optional[QgsLayerTree])

  • parent (Optional[QObject] = None)

ActionHierarchical = 65536
AllowLegendChangeState = 32768
AllowNodeChangeVisibility = 16384
AllowNodeRename = 8192
AllowNodeReorder = 4096
DeferredLegendInvalidation = 8
class Flag

Bases: int

class Flags
class Flags(f: QgsLayerTreeModel.Flags | QgsLayerTreeModel.Flag)
class Flags(a0: QgsLayerTreeModel.Flags)

Bases: object

ShowLegend = 1
ShowLegendAsTree = 4
UseEmbeddedWidgets = 16
UseTextFormatting = 32
UseThreadedHitTest = 131072
addLegendToLayer(self, nodeL: QgsLayerTreeLayer | None)[source]
Parameters:

nodeL (Optional[QgsLayerTreeLayer])

addTargetScreenProperties(self, properties: QgsScreenProperties)[source]

Adds additional target screen properties to use when generating icons for Qt.DecorationRole data.

This allows icons to be generated at an icon device pixel ratio and DPI which corresponds exactly to the view’s screen properties in which this model is used.

Added in version 3.32.

Parameters:

properties (QgsScreenProperties)

autoCollapseLegendNodes(self) int[source]

Returns at what number of legend nodes the layer node should be collapsed. -1 means no auto-collapse (default).

Return type:

int

connectToLayer(self, nodeLayer: QgsLayerTreeLayer | None)[source]
Parameters:

nodeLayer (Optional[QgsLayerTreeLayer])

connectToLayers(self, parentGroup: QgsLayerTreeGroup | None)[source]
Parameters:

parentGroup (Optional[QgsLayerTreeGroup])

connectToRootNode(self)[source]
currentIndex(self) QModelIndex[source]

Gets index of the item marked as current. Item marked as current is underlined.

Return type:

QModelIndex

disconnectFromLayer(self, nodeLayer: QgsLayerTreeLayer | None)[source]
Parameters:

nodeLayer (Optional[QgsLayerTreeLayer])

disconnectFromLayers(self, parentGroup: QgsLayerTreeGroup | None)[source]
Parameters:

parentGroup (Optional[QgsLayerTreeGroup])

disconnectFromRootNode(self)[source]
filterLegendNodes(self, nodes: Iterable[QgsLayerTreeModelLegendNode]) List[QgsLayerTreeModelLegendNode]

Filter nodes from QgsMapLayerLegend according to the current filtering rules

Parameters:

nodes (Iterable[QgsLayerTreeModelLegendNode])

Return type:

List[QgsLayerTreeModelLegendNode]

filterSettings(self) QgsLayerTreeFilterSettings | None[source]

Returns the filter settings to use to filter legend nodes. May be None.

Added in version 3.32.

Return type:

Optional[QgsLayerTreeFilterSettings]

findLegendNode(self, layerId: str | None, ruleKey: str | None) QgsLayerTreeModelLegendNode | None[source]

Searches through the layer tree to find a legend node with a matching layer ID and rule key.

Parameters:
  • layerId (Optional[str]) – map layer ID

  • ruleKey (Optional[str]) – legend node rule key

Return type:

Optional[QgsLayerTreeModelLegendNode]

Returns:

QgsLayerTreeModelLegendNode if found

virtual flags(self, index: QModelIndex) Qt.ItemFlags[source]

Returns OR-ed combination of model flags

Return type:

QgsLayerTreeModel.Flags

signal hitTestCompleted[source]

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

hitTestInProgress(self) bool[source]

Returns True if a hit test for visible legend items is currently in progress.

See also

hitTestStarted()

Added in version 3.32.

Return type:

bool

signal hitTestStarted[source]

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

static iconGroup() QIcon[source]
Return type:

QIcon

static index2legendNode(index: QModelIndex) QgsLayerTreeModelLegendNode | None[source]

Returns legend node for given index. Returns None for invalid index

Parameters:

index (QModelIndex)

Return type:

Optional[QgsLayerTreeModelLegendNode]

index2node(self, index: QModelIndex) QgsLayerTreeNode | None[source]

Returns layer tree node for given index. Returns root node for invalid index. Returns None if index does not refer to a layer tree node (e.g. it is a legend node)

Parameters:

index (QModelIndex)

Return type:

Optional[QgsLayerTreeNode]

indexOfParentLayerTreeNode(self, parentNode: QgsLayerTreeNode | None) QModelIndex[source]
Parameters:

parentNode (Optional[QgsLayerTreeNode])

Return type:

QModelIndex

indexes2nodes(self, list: Iterable[QModelIndex], skipInternal: bool = False) List[QgsLayerTreeNode]

Convert a list of indexes to a list of layer tree nodes. Indices that do not represent layer tree nodes are skipped. If skipInternal is True, a node is included in the output list only if no parent node is in the list.

Parameters:
  • list (Iterable[QModelIndex])

  • skipInternal (bool = False)

Return type:

List[QgsLayerTreeNode]

invalidateLegendMapBasedData(self)[source]
layerFlagsChanged(self)[source]

Triggered when layer flags have changed.

Added in version 3.18.

layerLegendChanged(self)[source]
layerLegendNodes(self, nodeLayer: QgsLayerTreeLayer | None, skipNodeEmbeddedInParent: bool = False) List[QgsLayerTreeModelLegendNode]

Returns filtered list of active legend nodes attached to a particular layer node (by default it returns also legend node embedded in parent layer node (if any) unless skipNodeEmbeddedInParent is True)

Note

Parameter skipNodeEmbeddedInParent added in QGIS 2.18

Parameters:
Return type:

List[QgsLayerTreeModelLegendNode]

layerNeedsUpdate(self)[source]
layerOriginalLegendNodes(self, nodeLayer: QgsLayerTreeLayer | None) List[QgsLayerTreeModelLegendNode]

Returns original (unfiltered) list of legend nodes attached to a particular layer node

Parameters:

nodeLayer (Optional[QgsLayerTreeLayer])

Return type:

List[QgsLayerTreeModelLegendNode]

layerStyleOverrides(self) Dict[str, str]

Gets map of map layer style overrides (key: layer ID, value: style name) where a different style should be used instead of the current one

Return type:

Dict[str, str]

layerTreeNodeFont(self, nodeType: int) QFont[source]

Gets font for a particular type of layer tree node. nodeType should come from QgsLayerTreeNode.NodeType enumeration

Parameters:

nodeType (int)

Return type:

QFont

legendCleanup(self)[source]
legendEmbeddedInParent(self, nodeLayer: QgsLayerTreeLayer | None) bool[source]
Parameters:

nodeLayer (Optional[QgsLayerTreeLayer])

Return type:

bool

legendFilterByScale(self) float[source]

Returns the scale which restricts the legend nodes which are visible. The scale value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map. A scale <= 0 indicates that no scale filtering is being performed.

Return type:

float

legendFilterMapSettings(self) QgsMapSettings | None[source]

Returns the current map settings used for the current legend filter (or None if none is enabled)

Return type:

Optional[QgsMapSettings]

legendIconEmbeddedInParent(self, nodeLayer: QgsLayerTreeLayer | None) QIcon[source]
Parameters:

nodeLayer (Optional[QgsLayerTreeLayer])

Return type:

QIcon

legendInvalidateMapBasedData(self)[source]
legendMapViewData(self)[source]

Gets hints about map view - to be used in legend nodes. Arguments that are not None will receive values. If there are no valid map view data (from previous call to setLegendMapViewData()), returned values are zeros.

legendNode2index(self, legendNode: QgsLayerTreeModelLegendNode | None) QModelIndex[source]

Returns index for a given legend node. If the legend node does not belong to the layer tree, the result is undefined. If the legend node is belongs to the tree but it is filtered out, invalid model index is returned.

Parameters:

legendNode (Optional[QgsLayerTreeModelLegendNode])

Return type:

QModelIndex

legendNodeData(self, node: QgsLayerTreeModelLegendNode | None, role: int) Any[source]
Parameters:
Return type:

Any

legendNodeDataChanged(self)[source]
legendNodeEmbeddedInParent(self, nodeLayer: QgsLayerTreeLayer | None) QgsLayerTreeModelLegendNode | None[source]

Returns legend node that may be embedded in parent (i.e. its icon will be used for layer’s icon).

Parameters:

nodeLayer (Optional[QgsLayerTreeLayer])

Return type:

Optional[QgsLayerTreeModelLegendNode]

legendNodeFlags(self, node: QgsLayerTreeModelLegendNode | None) Qt.ItemFlags[source]
Parameters:

node (Optional[QgsLayerTreeModelLegendNode])

Return type:

Qt.ItemFlags

legendNodeIndex(self, row: int, column: int, node: QgsLayerTreeModelLegendNode | None) QModelIndex[source]
Parameters:
Return type:

QModelIndex

legendNodeRowCount(self, node: QgsLayerTreeModelLegendNode | None) int[source]
Parameters:

node (Optional[QgsLayerTreeModelLegendNode])

Return type:

int

legendParent(self, legendNode: QgsLayerTreeModelLegendNode | None) QModelIndex[source]
Parameters:

legendNode (Optional[QgsLayerTreeModelLegendNode])

Return type:

QModelIndex

legendRootIndex(self, row: int, column: int, nL: QgsLayerTreeLayer | None) QModelIndex[source]
Parameters:
Return type:

QModelIndex

legendRootRowCount(self, nL: QgsLayerTreeLayer | None) int[source]
Parameters:

nL (Optional[QgsLayerTreeLayer])

Return type:

int

signal messageEmitted[source]

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

node2index(self, node: QgsLayerTreeNode | None) QModelIndex[source]

Returns index for a given node. If the node does not belong to the layer tree, the result is undefined

Parameters:

node (Optional[QgsLayerTreeNode])

Return type:

QModelIndex

nodeAddedChildren(self, node: QgsLayerTreeNode | None, indexFrom: int, indexTo: int)[source]
Parameters:
nodeCustomPropertyChanged(self, node: QgsLayerTreeNode | None, key: str | None)[source]
Parameters:
nodeLayerLoaded(self)[source]
nodeLayerWillBeUnloaded(self)[source]
nodeNameChanged(self, node: QgsLayerTreeNode | None, name: str | None)[source]

Updates model when node’s name has changed

Parameters:
nodeRemovedChildren(self)[source]
nodeVisibilityChanged(self, node: QgsLayerTreeNode | None)[source]
Parameters:

node (Optional[QgsLayerTreeNode])

nodeWillAddChildren(self, node: QgsLayerTreeNode | None, indexFrom: int, indexTo: int)[source]
Parameters:
nodeWillRemoveChildren(self, node: QgsLayerTreeNode | None, indexFrom: int, indexTo: int)[source]
Parameters:
recursivelyEmitDataChanged(self, index: QModelIndex = QModelIndex())[source]

emit dataChanged() for layer tree node items

Parameters:

index (QModelIndex = QModelIndex())

refreshLayerLegend(self, nodeLayer: QgsLayerTreeLayer | None)[source]

Force a refresh of legend nodes of a layer node. Not necessary to call when layer’s renderer is changed as the model listens to these events.

Parameters:

nodeLayer (Optional[QgsLayerTreeLayer])

refreshScaleBasedLayers(self, index: QModelIndex = QModelIndex(), previousScale: float = 0)[source]

Updates layer data for scale dependent layers, should be called when map scale changes. Emits dataChanged() for all scale dependent layers.

Parameters:
  • index (QModelIndex = QModelIndex())

  • previousScale (float = 0)

removeLegendFromLayer(self, nodeLayer: QgsLayerTreeLayer | None)[source]
Parameters:

nodeLayer (Optional[QgsLayerTreeLayer])

rootGroup(self) QgsLayerTree | None[source]

Returns pointer to the root node of the layer tree. Always a non None value.

Return type:

Optional[QgsLayerTree]

static scaleIconSize(standardSize: int) int[source]

Scales an layer tree model icon size to compensate for display pixel density, making the icon size hi-dpi friendly, whilst still resulting in pixel-perfect sizes for low-dpi displays.

standardSize should be set to a standard icon size, e.g. 16, 24, 48, etc.

Added in version 3.6.

Parameters:

standardSize (int)

Return type:

int

setAutoCollapseLegendNodes(self, nodeCount: int)[source]

Sets at what number of legend nodes the layer node should be collapsed. Setting -1 disables the auto-collapse (default).

Parameters:

nodeCount (int)

setCurrentIndex(self, currentIndex: QModelIndex)[source]

Sets index of the current item. May be used by view. Item marked as current is underlined.

Parameters:

currentIndex (QModelIndex)

setFilterSettings(self, settings: QgsLayerTreeFilterSettings | None = None)[source]

Sets the filter settings to use to filter legend nodes.

Set to None to disable legend filter.

See also

filterSettings()

Added in version 3.32.

Parameters:

settings (Optional[QgsLayerTreeFilterSettings] = None)

setFlag(self, f: QgsLayerTreeModel.Flag, on: bool = True)[source]

Enable or disable a model flag

Parameters:
setFlags(self, f: QgsLayerTreeModel.Flags | QgsLayerTreeModel.Flag)[source]

Sets OR-ed combination of model flags

Parameters:

f (Union[QgsLayerTreeModel.Flags, QgsLayerTreeModel.Flag])

setLayerStyleOverrides(self, overrides: Dict[str | None, str | None])[source]

Sets map of map layer style overrides (key: layer ID, value: style name) where a different style should be used instead of the current one

Parameters:

overrides (Dict[Optional[str], Optional[str]])

setLayerTreeNodeFont(self, nodeType: int, font: QFont)[source]

Sets font for a particular type of layer tree node. nodeType should come from QgsLayerTreeNode.NodeType enumeration

Parameters:
  • nodeType (int)

  • font (QFont)

setLegendFilter(self, settings: QgsMapSettings | None, useExtent: bool = True, polygon: QgsGeometry = QgsGeometry(), useExpressions: bool = True)[source]

Filter display of legend nodes for given map settings

Parameters:
  • settings (Optional[QgsMapSettings]) – Map settings. Setting None or invalid settings will disable any filter. Ownership is not changed, a copy is made

  • useExtent (bool = True) – Whether to use the extent of the map settings as a first spatial filter on legend nodes

  • polygon (QgsGeometry = QgsGeometry()) – If not empty, this polygon will be used instead of the map extent to filter legend nodes

  • useExpressions (bool = True) – Whether to use legend node filter expressions

Deprecated since version 3.32: Use setFilterSettings() instead.

setLegendFilterByMap(self, settings: QgsMapSettings | None)[source]

Force only display of legend nodes which are valid for given map settings. Setting None or invalid map settings will disable the functionality. Ownership of map settings pointer does not change, a copy is made.

Deprecated since version 3.32: Use setFilterSettings() instead.

Parameters:

settings (Optional[QgsMapSettings])

setLegendFilterByScale(self, scale: float)[source]

Force only display of legend nodes which are valid for a given scale. The scale value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map. Setting scale <= 0 will disable the functionality.

Parameters:

scale (float)

setLegendMapViewData(self, mapUnitsPerPixel: float, dpi: int, scale: float)[source]

Give the layer tree model hints about the currently associated map view so that legend nodes that use map units can be scaled correctly

Parameters:
  • mapUnitsPerPixel (float)

  • dpi (int)

  • scale (float)

setRootGroup(self, newRootGroup: QgsLayerTree | None)[source]

Reset the model and use a new root group node

Parameters:

newRootGroup (Optional[QgsLayerTree])

targetScreenProperties(self) Set[QgsScreenProperties]

Returns the target screen properties to use when generating icons.

This allows icons to be generated at an icon device pixel ratio and DPI which corresponds exactly to the view’s screen properties in which this model is used.

Added in version 3.32.

Return type:

Set[QgsScreenProperties]

testFlag(self, f: QgsLayerTreeModel.Flag) bool[source]

Check whether a flag is enabled

Parameters:

f (QgsLayerTreeModel.Flag)

Return type:

bool

waitForHitTestBlocking(self)[source]

When a current hit test for visible legend items is in progress, calling this method will block until that hit test is complete.

Added in version 3.32.