Class: QgsLayerTreeModel

class qgis.core.QgsLayerTreeModel(rootNode: QgsLayerTree, parent: QObject = None)

Bases: PyQt5.QtCore.QAbstractItemModel

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

The QgsLayerTreeModel class is model implementation for Qt item views framework. 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

New in version 2.4: Enums

Methods

addLegendToLayer

autoCollapseLegendNodes

Returns at what number of legend nodes the layer node should be collapsed.

beginInsertColumns

beginInsertRows

beginMoveColumns

beginMoveRows

beginRemoveColumns

beginRemoveRows

beginResetModel

changePersistentIndex

changePersistentIndexList

childEvent

columnCount

connectNotify

connectToLayer

connectToLayers

connectToRootNode

createIndex

currentIndex

Gets index of the item marked as current.

customEvent

data

decodeData

disconnectFromLayer

disconnectFromLayers

disconnectFromRootNode

disconnectNotify

dropMimeData

encodeData

endInsertColumns

endInsertRows

endMoveColumns

endMoveRows

endRemoveColumns

endRemoveRows

endResetModel

filterLegendNodes

Filter nodes from QgsMapLayerLegend according to the current filtering rules

findLegendNode

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

flags

flags(self) -> QgsLayerTreeModel.Flags Returns OR-ed combination of model flags

iconGroup

index

index2legendNode

Returns legend node for given index.

index2node

Returns layer tree node for given index.

indexOfParentLayerTreeNode

indexes2nodes

Convert a list of indexes to a list of layer tree nodes.

invalidateLegendMapBasedData

isSignalConnected

layerLegendChanged

layerLegendNodes

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)

layerNeedsUpdate

layerOriginalLegendNodes

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

layerStyleOverrides

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

layerTreeNodeFont

Gets font for a particular type of layer tree node.

legendCleanup

legendEmbeddedInParent

legendFilterByScale

Returns the scale which restricts the legend nodes which are visible.

legendFilterMapSettings

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

legendIconEmbeddedInParent

legendInvalidateMapBasedData

legendMapViewData

Gets hints about map view - to be used in legend nodes.

legendNode2index

Returns index for a given legend node.

legendNodeData

legendNodeDataChanged

legendNodeEmbeddedInParent

Returns legend node that may be embedded in parent (i.e.

legendNodeFlags

legendNodeIndex

legendNodeRowCount

legendParent

legendRootIndex

legendRootRowCount

mimeData

mimeTypes

node2index

Returns index for a given node.

nodeAddedChildren

nodeCustomPropertyChanged

nodeLayerLoaded

nodeLayerWillBeUnloaded

nodeNameChanged

Updates model when node’s name has changed

nodeRemovedChildren

nodeVisibilityChanged

nodeWillAddChildren

nodeWillRemoveChildren

parent

persistentIndexList

receivers

recursivelyEmitDataChanged

emit dataChanged() for layer tree node items

refreshLayerLegend

Force a refresh of legend nodes of a layer node.

refreshScaleBasedLayers

Updates layer data for scale dependent layers, should be called when map scale changes.

removeLegendFromLayer

removeRows

resetInternalData

rootGroup

Returns pointer to the root node of the layer tree.

rowCount

scaleIconSize

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.

sender

senderSignalIndex

setAutoCollapseLegendNodes

Sets at what number of legend nodes the layer node should be collapsed.

setCurrentIndex

Sets index of the current item.

setData

setFlag

Enable or disable a model flag

setFlags

Sets OR-ed combination of model flags

setLayerStyleOverrides

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

setLayerTreeNodeFont

Sets font for a particular type of layer tree node.

setLegendFilter

Filter display of legend nodes for given map settings

setLegendFilterByMap

Force only display of legend nodes which are valid for given map settings.

setLegendFilterByScale

Force only display of legend nodes which are valid for a given scale.

setLegendMapViewData

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

setRootGroup

Reset the model and use a new root group node

supportedDropActions

testFlag

Check whether a flag is enabled

timerEvent

Signals

Attributes

ActionHierarchical

AllowLegendChangeState

AllowNodeChangeVisibility

AllowNodeRename

AllowNodeReorder

DeferredLegendInvalidation

ShowLegend

ShowLegendAsTree

UseEmbeddedWidgets

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

Bases: int

class Flags

Bases: sip.wrapper

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

ShowLegend = 1
ShowLegendAsTree = 4
UseEmbeddedWidgets = 16
addLegendToLayer(self, nodeL: QgsLayerTreeLayer)
autoCollapseLegendNodes(self) → int

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

beginInsertColumns()
beginInsertRows()
beginMoveColumns()
beginMoveRows()
beginRemoveColumns()
beginRemoveRows()
beginResetModel()
changePersistentIndex()
changePersistentIndexList()
childEvent()
columnCount(self, parent: QModelIndex = QModelIndex()) → int
connectNotify()
connectToLayer(self, nodeLayer: QgsLayerTreeLayer)
connectToLayers(self, parentGroup: QgsLayerTreeGroup)
connectToRootNode(self)
createIndex()
currentIndex(self) → QModelIndex

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

customEvent()
data(self, index: QModelIndex, role: int = Qt.DisplayRole) → Any
decodeData()
disconnectFromLayer(self, nodeLayer: QgsLayerTreeLayer)
disconnectFromLayers(self, parentGroup: QgsLayerTreeGroup)
disconnectFromRootNode(self)
disconnectNotify()
dropMimeData(self, data: QMimeData, action: Qt.DropAction, row: int, column: int, parent: QModelIndex) → bool
encodeData()
endInsertColumns()
endInsertRows()
endMoveColumns()
endMoveRows()
endRemoveColumns()
endRemoveRows()
endResetModel()
filterLegendNodes(self, nodes: Iterable[QgsLayerTreeModelLegendNode]) → List[QgsLayerTreeModelLegendNode]

Filter nodes from QgsMapLayerLegend according to the current filtering rules

findLegendNode(self, layerId: str, ruleKey: str) → QgsLayerTreeModelLegendNode

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

Parameters
  • layerId – map layer ID

  • ruleKey – legend node rule key

Returns

QgsLayerTreeModelLegendNode if found

New in version 2.14.

flags(self, index: QModelIndex) → Qt.ItemFlags

flags(self) -> QgsLayerTreeModel.Flags Returns OR-ed combination of model flags

iconGroup() → QIcon
index(self, row: int, column: int, parent: QModelIndex = QModelIndex()) → QModelIndex
index2legendNode(index: QModelIndex) → QgsLayerTreeModelLegendNode

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

New in version 2.6.

index2node(self, index: QModelIndex) → QgsLayerTreeNode

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)

indexOfParentLayerTreeNode(self, parentNode: QgsLayerTreeNode) → QModelIndex
indexes2nodes(self, list: object, 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.

invalidateLegendMapBasedData(self)
isSignalConnected()
layerLegendChanged(self)
layerLegendNodes(self, nodeLayer: QgsLayerTreeLayer, 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

New in version 2.6.

layerNeedsUpdate(self)
layerOriginalLegendNodes(self, nodeLayer: QgsLayerTreeLayer) → List[QgsLayerTreeModelLegendNode]

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

New in version 2.14.

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

New in version 2.10.

layerTreeNodeFont(self, nodeType: int) → QFont

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

legendCleanup(self)
legendEmbeddedInParent(self, nodeLayer: QgsLayerTreeLayer) → bool
legendFilterByScale(self) → float

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.

New in version 2.6.

legendFilterMapSettings(self) → QgsMapSettings

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

New in version 2.14.

legendIconEmbeddedInParent(self, nodeLayer: QgsLayerTreeLayer) → QIcon
legendInvalidateMapBasedData(self)
legendMapViewData(self) → Tuple[float, int, float]

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.

New in version 2.6.

legendNode2index(self, legendNode: QgsLayerTreeModelLegendNode) → QModelIndex

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.

New in version 2.6.

legendNodeData(self, node: QgsLayerTreeModelLegendNode, role: int) → Any
legendNodeDataChanged(self)
legendNodeEmbeddedInParent(self, nodeLayer: QgsLayerTreeLayer) → QgsLayerTreeModelLegendNode

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

New in version 2.18.

legendNodeFlags(self, node: QgsLayerTreeModelLegendNode) → Qt.ItemFlags
legendNodeIndex(self, row: int, column: int, node: QgsLayerTreeModelLegendNode) → QModelIndex
legendNodeRowCount(self, node: QgsLayerTreeModelLegendNode) → int
legendParent(self, legendNode: QgsLayerTreeModelLegendNode) → QModelIndex
legendRootIndex(self, row: int, column: int, nL: QgsLayerTreeLayer) → QModelIndex
legendRootRowCount(self, nL: QgsLayerTreeLayer) → int
mimeData(self, indexes: object) → QMimeData
mimeTypes(self) → List[str]
node2index(self, node: QgsLayerTreeNode) → QModelIndex

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

nodeAddedChildren(self, node: QgsLayerTreeNode, indexFrom: int, indexTo: int)
nodeCustomPropertyChanged(self, node: QgsLayerTreeNode, key: str)
nodeLayerLoaded(self)
nodeLayerWillBeUnloaded(self)
nodeNameChanged(self, node: QgsLayerTreeNode, name: str)

Updates model when node’s name has changed

New in version 3.0.

nodeRemovedChildren(self)
nodeVisibilityChanged(self, node: QgsLayerTreeNode)
nodeWillAddChildren(self, node: QgsLayerTreeNode, indexFrom: int, indexTo: int)
nodeWillRemoveChildren(self, node: QgsLayerTreeNode, indexFrom: int, indexTo: int)
parent(self, child: QModelIndex) → QModelIndex
persistentIndexList()
receivers()
recursivelyEmitDataChanged(self, index: QModelIndex = QModelIndex())

emit dataChanged() for layer tree node items

refreshLayerLegend(self, nodeLayer: QgsLayerTreeLayer)

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.

refreshScaleBasedLayers(self, index: QModelIndex = QModelIndex())

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

New in version 2.16.

removeLegendFromLayer(self, nodeLayer: QgsLayerTreeLayer)
removeRows(self, row: int, count: int, parent: QModelIndex = QModelIndex()) → bool
resetInternalData()
rootGroup(self) → QgsLayerTree

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

rowCount(self, parent: QModelIndex = QModelIndex()) → int
scaleIconSize(standardSize: int) → int

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.

New in version 3.6.

sender()
senderSignalIndex()
setAutoCollapseLegendNodes(self, nodeCount: int)

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

setCurrentIndex(self, currentIndex: QModelIndex)

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

setData(self, index: QModelIndex, value: Any, role: int = Qt.EditRole) → bool
setFlag(self, f: QgsLayerTreeModel.Flag, on: bool = True)

Enable or disable a model flag

setFlags(self, f: Union[QgsLayerTreeModel.Flags, QgsLayerTreeModel.Flag])

Sets OR-ed combination of model flags

setLayerStyleOverrides(self, overrides: Dict[str, str])

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

New in version 2.10.

setLayerTreeNodeFont(self, nodeType: int, font: QFont)

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

setLegendFilter(self, settings: QgsMapSettings, useExtent: bool = True, polygon: QgsGeometry = QgsGeometry(), useExpressions: bool = True)

Filter display of legend nodes for given map settings

Parameters
  • settings – Map settings. Setting None or invalid settings will disable any filter. Ownership is not changed, a copy is made

  • useExtent – Whether to use the extent of the map settings as a first spatial filter on legend nodes

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

  • useExpressions – Whether to use legend node filter expressions

New in version 2.14.

setLegendFilterByMap(self, settings: QgsMapSettings)

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.

New in version 2.6.

setLegendFilterByScale(self, scale: float)

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.

New in version 2.6.

setLegendMapViewData(self, mapUnitsPerPixel: float, dpi: int, scale: float)

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

New in version 2.6.

setRootGroup(self, newRootGroup: QgsLayerTree)

Reset the model and use a new root group node

New in version 2.6.

supportedDropActions(self) → Qt.DropActions
testFlag(self, f: QgsLayerTreeModel.Flag) → bool

Check whether a flag is enabled

timerEvent()