QGIS API Documentation
3.14.0-Pi (9f7028fd23)
|
Go to the documentation of this file.
17 #include <QTextStream>
40 : QAbstractItemModel( parent )
41 , mRootNode( rootNode )
42 , mFlags( ShowLegend | AllowLegendChangeState | DeferredLegendInvalidation )
43 , mAutoCollapseLegendNodesCount( -1 )
44 , mLegendFilterByScale( 0 )
45 , mLegendFilterUsesExtent( false )
46 , mLegendMapViewMupp( 0 )
47 , mLegendMapViewDpi( 0 )
48 , mLegendMapViewScale( 0 )
65 if ( !
index.isValid() )
68 QObject *obj =
reinterpret_cast<QObject *
>(
index.internalPointer() );
69 return qobject_cast<QgsLayerTreeNode *>( obj );
103 return QModelIndex();
110 return QModelIndex();
117 return createIndex( row, column,
static_cast<QObject *
>( n->
children().at( row ) ) );
123 if ( !child.isValid() )
124 return QModelIndex();
137 return QModelIndex();
145 Q_ASSERT( parentNode );
148 if ( !grandParentNode )
149 return QModelIndex();
151 int row = grandParentNode->
children().indexOf( parentNode );
152 Q_ASSERT( row >= 0 );
154 return createIndex( row, 0,
static_cast<QObject *
>( parentNode ) );
167 if ( role == Qt::DisplayRole || role == Qt::EditRole )
175 QString name = nodeLayer->
name();
176 if ( nodeLayer->
customProperty( QStringLiteral(
"showFeatureCount" ), 0 ).toInt() && role == Qt::DisplayRole )
180 name += QStringLiteral(
" [%1]" ).arg( vlayer->
featureCount() );
185 else if ( role == Qt::DecorationRole &&
index.column() == 0 )
199 switch ( layer->
type() )
242 QPainter painter( &pixmap );
246 icon = QIcon( pixmap );
252 else if ( role == Qt::CheckStateRole )
276 f.setUnderline(
true );
282 f.setItalic( !f.italic() );
289 QBrush brush( qApp->palette().color( QPalette::Text ), Qt::SolidPattern );
295 QColor fadedTextColor = brush.color();
296 fadedTextColor.setAlpha( 128 );
297 brush.setColor( fadedTextColor );
302 else if ( role == Qt::ToolTipRole )
309 !layer->
title().isEmpty() ? layer->title() :
310 !layer->shortName().isEmpty() ? layer->shortName() :
313 title =
"<b>" + title.toHtmlEscaped() +
"</b>";
315 if ( layer->isSpatial() && layer->crs().isValid() )
317 if (
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
320 title += tr(
" (%1)" ).arg( layer->crs().authid() ).toHtmlEscaped();
326 if ( !layer->abstract().isEmpty() )
329 const QStringList abstractLines = layer->abstract().split(
'\n' );
330 for (
const auto &l : abstractLines )
332 parts << l.toHtmlEscaped();
337 QString source( layer->publicSource() );
338 if ( source.size() > 1024 )
340 source = source.left( 1023 ) + QString( QChar( 0x2026 ) );
343 parts <<
"<i>" + source.toHtmlEscaped() +
"</i>";
345 return parts.join( QStringLiteral(
"<br/>" ) );
356 if ( !
index.isValid() )
358 Qt::ItemFlags rootFlags = Qt::ItemFlags();
360 rootFlags |= Qt::ItemIsDropEnabled;
367 Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
370 f |= Qt::ItemIsEditable;
373 bool isEmbedded = node->
customProperty( QStringLiteral(
"embedded" ) ).toInt();
378 if ( !isEmbedded || ( isEmbedded && node->
parent() && !node->
parent()->
customProperty( QStringLiteral(
"embedded" ) ).toInt() ) )
379 f |= Qt::ItemIsDragEnabled;
383 f |= Qt::ItemIsUserCheckable;
386 f |= Qt::ItemIsDropEnabled;
398 bool res = sym->
setData( value, role );
406 return QAbstractItemModel::setData(
index, value, role );
408 if ( role == Qt::CheckStateRole )
413 bool checked =
static_cast< Qt::CheckState
>( value.toInt() ) == Qt::Checked;
414 if ( checked && node->
children().isEmpty() )
434 else if ( role == Qt::EditRole )
442 layer->
setName( value.toString() );
452 return QAbstractItemModel::setData(
index, value, role );
457 if ( !node || !node->
parent() )
458 return QModelIndex();
463 Q_ASSERT( row >= 0 );
464 return index( row, 0, parentIndex );
473 if ( child->
parent() == node )
476 return _isChildOfNode( child->
parent(), node );
479 static bool _isChildOfNodes(
QgsLayerTreeNode *child,
const QList<QgsLayerTreeNode *> &nodes )
483 if ( _isChildOfNode( child, n ) )
493 QList<QgsLayerTreeNode *> nodes;
494 const auto constList = list;
495 for (
const QModelIndex &
index : constList )
508 QList<QgsLayerTreeNode *> nodesFinal;
511 if ( !_isChildOfNodes( node, nodes ) )
542 emit dataChanged( idx, idx );
546 if ( oldNodeCount > 0 )
548 beginRemoveRows( idx, 0, oldNodeCount - 1 );
571 if ( oldIndex.isValid() )
572 emit dataChanged( oldIndex, oldIndex );
641 if ( useExpressions )
648 if ( enabled && !expr.isEmpty() )
650 exprs[ nodeLayer->layerId()] = expr;
655 if ( useExpressions && !useExtent && !polygonValid )
721 QFontMetrics fm( ( QFont() ) );
722 const double scale = 1.1 * standardSize / 24;
723 return static_cast< int >( std::floor( std::max(
Qgis::UI_SCALE_FACTOR * fm.height() * scale,
static_cast< double >( standardSize ) ) ) );
729 beginInsertRows(
node2index( node ), indexFrom, indexTo );
732 static QList<QgsLayerTreeLayer *> _layerNodesInSubtree(
QgsLayerTreeNode *node,
int indexFrom,
int indexTo )
734 QList<QgsLayerTreeNode *> children = node->
children();
735 QList<QgsLayerTreeLayer *> newLayerNodes;
736 for (
int i = indexFrom; i <= indexTo; ++i )
744 return newLayerNodes;
753 const auto subNodes = _layerNodesInSubtree( node, indexFrom, indexTo );
762 beginRemoveRows(
node2index( node ), indexFrom, indexTo );
765 const auto subNodes = _layerNodesInSubtree( node, indexFrom, indexTo );
830 QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
843 QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
854 if ( nodeLayer->
customProperty( QStringLiteral(
"showFeatureCount" ) ).toInt() )
866 if (
index.isValid() )
873 if ( !nodeLayer->
layer() )
915 const auto constChildren = group->
children();
933 disconnect( nodeLayer,
nullptr,
this,
nullptr );
935 if ( !nodeLayer->
layer() )
946 disconnect( nodeLayer->
layer(),
nullptr,
this,
nullptr );
952 const auto constChildren = parentGroup->
children();
964 const auto constChildren = parentGroup->
children();
992 disconnect(
mRootNode,
nullptr,
this,
nullptr );
1003 int count = node->
children().count();
1006 emit dataChanged(
index( 0, 0, idx ),
index( count - 1, 0, idx ) );
1007 for (
int i = 0; i < count; ++i )
1022 emit dataChanged( idx, idx );
1025 int count = node->
children().count();
1026 for (
int i = 0; i < count; ++i )
1032 return Qt::CopyAction | Qt::MoveAction;
1038 types << QStringLiteral(
"application/qgis.layertreemodeldata" );
1046 QModelIndexList sortedIndexes = indexes;
1047 std::sort( sortedIndexes.begin(), sortedIndexes.end(), std::less<QModelIndex>() );
1049 QList<QgsLayerTreeNode *> nodesFinal =
indexes2nodes( sortedIndexes,
true );
1051 if ( nodesFinal.isEmpty() )
1054 QMimeData *
mimeData =
new QMimeData();
1056 QDomDocument layerTreeDoc;
1057 QDomElement rootLayerTreeElem = layerTreeDoc.createElement( QStringLiteral(
"layer_tree_model_data" ) );
1063 layerTreeDoc.appendChild( rootLayerTreeElem );
1065 QString errorMessage;
1067 QDomDocument layerDefinitionsDoc( QStringLiteral(
"qgis-layer-definition" ) );
1070 QString txt = layerDefinitionsDoc.toString();
1072 mimeData->setData( QStringLiteral(
"application/qgis.layertreemodeldata" ), layerTreeDoc.toString().toUtf8() );
1073 mimeData->setData( QStringLiteral(
"application/qgis.application.pid" ), QString::number( QCoreApplication::applicationPid() ).toUtf8() );
1074 mimeData->setData( QStringLiteral(
"application/qgis.layertree.layerdefinitions" ), txt.toUtf8() );
1082 if ( action == Qt::IgnoreAction )
1085 if ( !
data->hasFormat( QStringLiteral(
"application/qgis.layertreemodeldata" ) ) )
1095 if (
parent.isValid() && row == -1 )
1101 qint64 qgisPid =
data->data( QStringLiteral(
"application/qgis.application.pid" ) ).toInt( &ok );
1103 if ( ok && qgisPid != QCoreApplication::applicationPid() )
1105 QByteArray encodedLayerDefinitionData =
data->data( QStringLiteral(
"application/qgis.layertree.layerdefinitions" ) );
1106 QDomDocument layerDefinitionDoc;
1107 if ( !layerDefinitionDoc.setContent( QString::fromUtf8( encodedLayerDefinitionData ) ) )
1110 QString errorMessage;
1112 emit
messageEmitted( tr(
"New layers added from another QGIS instance" ) );
1116 QByteArray encodedLayerTreeData =
data->data( QStringLiteral(
"application/qgis.layertreemodeldata" ) );
1118 QDomDocument layerTreeDoc;
1119 if ( !layerTreeDoc.setContent( QString::fromUtf8( encodedLayerTreeData ) ) )
1122 QDomElement rootLayerTreeElem = layerTreeDoc.documentElement();
1123 if ( rootLayerTreeElem.tagName() != QLatin1String(
"layer_tree_model_data" ) )
1126 QList<QgsLayerTreeNode *> nodes;
1128 QDomElement elem = rootLayerTreeElem.firstChildElement();
1129 while ( !elem.isNull() )
1135 elem = elem.nextSiblingElement();
1138 if ( nodes.isEmpty() )
1177 return mFlags.testFlag( f );
1187 QList<QgsLayerTreeModelLegendNode *> filtered;
1207 if (
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( node->layerNode()->layer() ) )
1237 const auto constMLegend =
mLegend;
1240 qDeleteAll(
data.originalNodes );
1249 if (
mLegend.contains( nodeLayer ) )
1251 qDeleteAll(
mLegend[nodeLayer].originalNodes );
1252 delete mLegend[nodeLayer].tree;
1260 if ( !nodeL || !nodeL->
layer() )
1280 int widgetsCount = ml->
customProperty( QStringLiteral(
"embeddedWidgets/count" ), 0 ).toInt();
1281 while ( widgetsCount > 0 )
1283 lstNew.insert( 0,
new EmbeddedWidgetLegendNode( nodeL ) );
1288 QList<QgsLayerTreeModelLegendNode *> filteredLstNew =
filterLegendNodes( lstNew );
1290 const auto constLstNew = lstNew;
1293 n->setParent(
this );
1301 const auto constFilteredLstNew = filteredLstNew;
1318 int count = legendTree ? legendTree->
children[
nullptr].count() : filteredLstNew.count();
1320 if ( !filteredLstNew.isEmpty() ) beginInsertRows(
node2index( nodeL ), 0, count - 1 );
1323 data.originalNodes = lstNew;
1324 data.activeNodes = filteredLstNew;
1325 data.embeddedNodeInParent = embeddedNode;
1326 data.tree = legendTree;
1330 if ( !filteredLstNew.isEmpty() ) endInsertRows();
1341 bool hasParentKeys =
false;
1346 hasParentKeys =
true;
1350 if ( !hasParentKeys )
1354 QHash<QString, QgsLayerTreeModelLegendNode *> rule2node;
1355 rule2node[QString()] =
nullptr;
1359 if ( ruleKey.isEmpty() )
1361 if ( rule2node.contains( ruleKey ) )
1363 rule2node[ruleKey] = n;
1388 context->setScaleFactor( dpi / 25.4 );
1389 context->setRendererScale( scale );
1392 return validData ? context.release() :
nullptr;
1398 return qobject_cast<QgsLayerTreeModelLegendNode *>(
reinterpret_cast<QObject *
>(
index.internalPointer() ) );
1410 int row =
data.tree->children[parentLegendNode].indexOf(
legendNode );
1411 return index( row, 0, parentIndex );
1417 return index( row, 0, parentIndex );
1422 Q_ASSERT( parentIndex.isValid() );
1425 return QModelIndex();
1427 return index( row, 0, parentIndex );
1435 return data.tree->children[node].count();
1443 if ( !
mLegend.contains( nL ) )
1448 return data.tree->children[
nullptr].count();
1450 int count =
data.activeNodes.count();
1457 Q_ASSERT(
mLegend.contains( nL ) );
1460 return createIndex( row, column,
static_cast<QObject *
>(
data.tree->children[
nullptr].at( row ) ) );
1462 return createIndex( row, column,
static_cast<QObject *
>(
data.activeNodes.at( row ) ) );
1470 return createIndex( row, column,
static_cast<QObject *
>(
data.tree->children[node].at( row ) ) );
1472 return QModelIndex();
1485 int row =
data.tree->children[grandParentNode].indexOf( parentNode );
1486 return createIndex( row, 0,
static_cast<QObject *
>( parentNode ) );
1500 return node->
data( role );
1506 Qt::ItemFlags f = node->
flags();
1508 f &= ~Qt::ItemIsUserCheckable;
1515 return static_cast< bool >(
mLegend[nodeLayer].embeddedNodeInParent );
1520 return mLegend[nodeLayer].embeddedNodeInParent;
1529 return QIcon( qvariant_cast<QPixmap>(
legendNode->
data( Qt::DecorationRole ) ) );
1535 if ( !
mLegend.contains( nodeLayer ) )
1536 return QList<QgsLayerTreeModelLegendNode *>();
1539 QList<QgsLayerTreeModelLegendNode *> lst(
data.activeNodes );
1540 if ( !skipNodeEmbeddedInParent &&
data.embeddedNodeInParent )
1541 lst.prepend(
data.embeddedNodeInParent );
1547 return mLegend.value( nodeLayer ).originalNodes;
1552 for (
auto it =
mLegend.constBegin(); it !=
mLegend.constEnd(); ++it )
1555 if ( layer->
layerId() == layerId )
1557 const auto activeNodes =
mLegend.value( layer ).activeNodes;
1590 std::unique_ptr<QgsRenderContext> context( createTemporaryRenderContext() );
1594 QList<QgsSymbolLegendNode *> symbolNodes;
1595 QMap<QString, int> widthMax;
1603 widthMax[parentKey] = std::max( sz.width(), widthMax.contains( parentKey ) ? widthMax[parentKey] : 0 );
1605 symbolNodes.append( n );
1608 const auto constSymbolNodes = symbolNodes;
1612 Q_ASSERT( widthMax[parentKey] > 0 );
1613 const int twiceMarginWidth = 2;
1614 n->setIconSize( QSize( widthMax[parentKey] + twiceMarginWidth, n->iconSize().rheight() + twiceMarginWidth ) );
@ NodeGroup
Container of other groups and layers.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets map of map layer style overrides (key: layer ID, value: style name) where a different style shou...
int columnCount(const QModelIndex &parent=QModelIndex()) const override
QgsLayerTreeLayer * findLayer(QgsMapLayer *layer) const
Find layer node representing the map layer.
QList< QgsLayerTreeLayer * > findLayers() const
Find all layer nodes.
void nodeWillRemoveChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
static void applyLayerNodeProperties(QgsLayerTreeLayer *nodeLayer, QList< QgsLayerTreeModelLegendNode * > &nodes)
update according to layer node's custom properties (order of items, user labels for items)
QgsLayerTree * mRootNode
Pointer to the root node of the layer tree. Not owned by the model.
void disconnectFromRootNode()
QModelIndex currentIndex() const
Gets index of the item marked as current. Item marked as current is underlined.
virtual bool isEmbeddedInParent() const
Qt::ItemFlags legendNodeFlags(QgsLayerTreeModelLegendNode *node) const
void nodeLayerWillBeUnloaded()
void addLegendToLayer(QgsLayerTreeLayer *nodeL)
LayerLegendTree * tryBuildLegendTree(const QList< QgsLayerTreeModelLegendNode * > &nodes)
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
QModelIndex indexOfParentLayerTreeNode(QgsLayerTreeNode *parentNode) const
void removeChildren(int from, int count)
Remove child nodes from index "from".
QMap< QgsLayerTreeModelLegendNode *, QList< QgsLayerTreeModelLegendNode * > > children
List of children for each active node. Top-level nodes are under nullptr key. Pointers are not owned.
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
void setItemVisibilityChecked(bool checked)
Check or uncheck a node (independently of its ancestors or children)
void removedChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes has been removed from a node within the tree.
virtual void invalidateMapBasedData()
Notification from model that information from associated map view has changed.
virtual QVariant data(int role) const =0
Returns data associated with the item. Must be implemented in derived class.
void layerModified()
Emitted when modifications has been done on layer.
QList< QgsLayerTreeModelLegendNode * > filterLegendNodes(const QList< QgsLayerTreeModelLegendNode * > &nodes)
Filter nodes from QgsMapLayerLegend according to the current filtering rules.
void layerLoaded()
Emitted when a previously unavailable layer got loaded.
#define QgsDebugMsgLevel(str, level)
QgsLayerTreeModelLegendNode * findLegendNode(const QString &layerId, const QString &ruleKey) const
Searches through the layer tree to find a legend node with a matching layer ID and rule key.
QString layerId() const
Returns the ID for the map layer associated with this node.
void recursivelyEmitDataChanged(const QModelIndex &index=QModelIndex())
emit dataChanged() for layer tree node items
double mLegendMapViewMupp
static QIcon iconDefault()
static QByteArray layerTreeNodesToUriList(const QList< QgsLayerTreeNode * > &nodes)
Returns encoded URI list from a list of layer tree nodes.
@ NodeLayer
Leaf node pointing to a layer.
QFont layerTreeNodeFont(int nodeType) const
Gets font for a particular type of layer tree node. nodeType should come from QgsLayerTreeNode::NodeT...
@ AllowLegendChangeState
Allow check boxes for legend nodes (if supported by layer's legend)
QHash< QgsLayerTreeLayer *, LayerLegendData > mLegend
Per layer data about layer's legend nodes.
QMimeData * mimeData(const QModelIndexList &indexes) const override
bool legendEmbeddedInParent(QgsLayerTreeLayer *nodeLayer) const
void messageEmitted(const QString &message, Qgis::MessageLevel level=Qgis::Info, int duration=5)
Emits a message than can be displayed to the user in a GUI class.
static QIcon iconRaster()
QModelIndex parent(const QModelIndex &child) const override
bool hasValidSettings() const
Check whether the map settings are valid and can be used for rendering.
void nodeWillAddChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Flags mFlags
Sets of flags for the model.
std::unique_ptr< QgsMapHitTest > mLegendFilterHitTest
QMap< QString, QString > LayerFilterExpression
Maps an expression string to a layer id.
void removeLegendFromLayer(QgsLayerTreeLayer *nodeLayer)
static QgsProject * instance()
Returns the QgsProject singleton instance.
void setFlags(QgsLayerTreeModel::Flags f)
Sets OR-ed combination of model flags.
bool testFlag(Flag f) const
Check whether a flag is enabled.
std::unique_ptr< QgsMapSettings > mLegendFilterMapSettings
bool mLegendFilterUsesExtent
whether to use map filtering
void customPropertyChanged(QgsLayerTreeNode *node, const QString &key)
Emitted when a custom property of a node within the tree has been changed or removed.
virtual QList< QgsLayerTreeModelLegendNode * > createLayerTreeModelLegendNodes(QgsLayerTreeLayer *nodeLayer)=0
Returns list of legend nodes to be used for a particular layer tree layer node.
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
void nameChanged(QgsLayerTreeNode *node, QString name)
Emitted when the name of the node is changed.
QString name() const override
Returns the layer's name.
QgsLayerTreeModelLegendNode * legendNodeEmbeddedInParent(QgsLayerTreeLayer *nodeLayer) const
Returns legend node that may be embedded in parent (i.e.
void nodeCustomPropertyChanged(QgsLayerTreeNode *node, const QString &key)
@ ShowLegendAsTree
For legends that support it, will show them in a tree instead of a list (needs also ShowLegend)....
QVariant legendNodeData(QgsLayerTreeModelLegendNode *node, int role) const
long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
QgsMapLayerLegend * legend() const
Can be nullptr.
void layerLegendChanged()
void disconnectFromLayer(QgsLayerTreeLayer *nodeLayer)
void setItemVisibilityCheckedParentRecursive(bool checked)
Check or uncheck a node and all its parents.
@ ActionHierarchical
Check/uncheck action has consequences on children (or parents for leaf node)
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
static QgsLayerTreeGroup * toGroup(QgsLayerTreeNode *node)
Cast node to a group.
@ AllowNodeRename
Allow renaming of groups and layers.
void disconnectFromLayers(QgsLayerTreeGroup *parentGroup)
QSize iconSize(bool dockableToolbar)
Returns the user-preferred size of a window's toolbar icons.
NodeType nodeType() const
Find out about type of the node. It is usually shorter to use convenience functions from QgsLayerTree...
virtual Qt::ItemFlags flags() const
Returns item flags associated with the item. Default implementation returns Qt::ItemIsEnabled.
static int scaleIconSize(int standardSize)
Scales an layer tree model icon size to compensate for display pixel density, making the icon size hi...
void legendNodeDataChanged()
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override
bool removeRows(int row, int count, const QModelIndex &parent=QModelIndex()) override
QModelIndex legendNode2index(QgsLayerTreeModelLegendNode *legendNode)
Returns index for a given legend node.
QModelIndex node2index(QgsLayerTreeNode *node) const
Returns index for a given node. If the node does not belong to the layer tree, the result is undefine...
bool isInScaleRange(double scale) const
Tests whether the layer should be visible at the specified scale.
static QgsLayerTreeModelLegendNode * index2legendNode(const QModelIndex &index)
Returns legend node for given index.
void editingStarted()
Emitted when editing on this layer has started.
~QgsLayerTreeModel() override
void setLayerTreeNodeFont(int nodeType, const QFont &font)
Sets font for a particular type of layer tree node. nodeType should come from QgsLayerTreeNode::NodeT...
void nodeAddedChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
QMap< QString, QString > layerStyleOverrides() const
Gets map of map layer style overrides (key: layer ID, value: style name) where a different style shou...
QPersistentModelIndex mCurrentIndex
Current index - will be underlined.
void connectToLayers(QgsLayerTreeGroup *parentGroup)
QModelIndex legendParent(QgsLayerTreeModelLegendNode *legendNode) const
void setName(const QString &n) override
Sets the layer's name.
@ DeferredLegendInvalidation
Defer legend model invalidation.
void setLegendFilterByScale(double scale)
Force only display of legend nodes which are valid for a given scale.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
QTimer mDeferLegendInvalidationTimer
void refreshLayerLegend(QgsLayerTreeLayer *nodeLayer)
Force a refresh of legend nodes of a layer node.
QModelIndex legendNodeIndex(int row, int column, QgsLayerTreeModelLegendNode *node) const
static QIcon iconVectorTile()
Returns icon for vector tile layer.
int rowCount(const QModelIndex &parent=QModelIndex()) const override
virtual void writeXml(QDomElement &parentElement, const QgsReadWriteContext &context)=0
Write layer tree to XML.
void setIconSize(QSize sz)
Set the icon size.
Structure that stores all data associated with one map layer.
double mLegendFilterByScale
scale denominator for filtering of legend nodes (<= 0 means no filtering)
void setLegendFilterByMap(const QgsMapSettings *settings)
Force only display of legend nodes which are valid for given map settings.
Structure that stores tree representation of map layer's legend.
void setName(const QString &n) override
Sets the group's name.
void insertChildNodes(int index, const QList< QgsLayerTreeNode * > &nodes)
Insert existing nodes at specified position.
static const double UI_SCALE_FACTOR
UI scaling factor.
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
QString title() const
Returns the title of the layer used by QGIS Server in GetCapabilities request.
void setAutoCollapseLegendNodes(int nodeCount)
Sets at what number of legend nodes the layer node should be collapsed. Setting -1 disables the auto-...
QMap< QgsLayerTreeModelLegendNode *, QgsLayerTreeModelLegendNode * > parents
Pointer to parent for each active node. Top-level nodes have nullptr parent. Pointers are not owned.
@ ParentRuleKeyRole
Rule key of the parent legend node - for legends with tree hierarchy (QString). Added in 2....
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
QgsMapLayer * layer() const
Returns the map layer associated with this node.
Qt::DropActions supportedDropActions() const override
void setRootGroup(QgsLayerTree *newRootGroup)
Reset the model and use a new root group node.
QIcon legendIconEmbeddedInParent(QgsLayerTreeLayer *nodeLayer) const
static QgsLayerTreeNode * readXml(QDomElement &element, const QgsReadWriteContext &context)
Read layer tree from XML.
int autoCollapseLegendNodes() const
Returns at what number of legend nodes the layer node should be collapsed. -1 means no auto-collapse ...
static QIcon iconPolygon()
QgsLayerTree * rootGroup() const
Returns pointer to the root node of the layer tree. Always a non nullptr value.
QgsLayerTreeModelLegendNode * legendNode(const QString &rule, QgsLayerTreeModel &model)
void legendChanged()
Signal emitted when legend of the layer has changed.
void layerWillBeUnloaded()
Emitted when a previously available layer got unloaded (from layer registry).
QgsLayerTreeNode * index2node(const QModelIndex &index) const
Returns layer tree node for given index.
void legendMapViewData(double *mapUnitsPerPixel, int *dpi, double *scale) const
Gets hints about map view - to be used in legend nodes.
void willAddChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes will be added to a node within the tree.
virtual void setItemVisibilityCheckedRecursive(bool checked)
Check or uncheck a node and all its children (taking into account exclusion rules)
virtual bool setData(const QVariant &value, int role)
Sets some data associated with the item. Default implementation does nothing and returns false.
static bool loadLayerDefinition(const QString &path, QgsProject *project, QgsLayerTreeGroup *rootGroup, QString &errorMessage)
Loads the QLR at path into QGIS. New layers are added to given project into layer tree specified by r...
int legendNodeRowCount(QgsLayerTreeModelLegendNode *node) const
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
void editingStopped()
Emitted when edited changes have been successfully written to the data provider.
QgsLayerTreeLayer * layerNode() const
Returns pointer to the parent layer node.
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
static bool exportLayerDefinition(QString path, const QList< QgsLayerTreeNode * > &selectedTreeNodes, QString &errorMessage)
Export the selected layer tree nodes to a QLR file.
static QIcon iconMesh()
Returns icon for mesh layer type.
QStringList mimeTypes() const override
double mLegendMapViewScale
void setFlag(Flag f, bool on=true)
Enable or disable a model flag.
QModelIndex legendRootIndex(int row, int column, QgsLayerTreeLayer *nL) const
bool itemVisibilityChecked() const
Returns whether a node is checked (independently of its ancestors or children)
QVariant customProperty(const QString &key, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer. Properties are stored in a map and saved in project file.
Flags flags() const
Returns OR-ed combination of model flags.
static QString displayString(Type type)
Returns a display string type for a WKB type, e.g., the geometry name used in WKT geometry representa...
QMap< QString, QString > mLayerStyleOverrides
Overrides of map layers' styles: key = layer ID, value = style XML.
@ UseTextFormatting
Layer nodes will alter text appearance based on layer properties, such as scale based visibility.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
@ VectorTileLayer
Added in 3.14.
void setLegendFilter(const QgsMapSettings *settings, bool useExtent=true, const QgsGeometry &polygon=QgsGeometry(), bool useExpressions=true)
Filter display of legend nodes for given map settings.
static QPixmap getThemePixmap(const QString &name)
Helper to get a theme icon as a pixmap.
QVariant data(int role) const override
Returns data associated with the item. Must be implemented in derived class.
void setLegendMapViewData(double mapUnitsPerPixel, int dpi, double scale)
Give the layer tree model hints about the currently associated map view so that legend nodes that use...
QString name() const override
Returns the group's name.
void addedChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes have been added to a node within the tree.
int mAutoCollapseLegendNodesCount
Minimal number of nodes when legend should be automatically collapsed. -1 = disabled.
void setOverrideStyle(const QString &style)
Temporarily apply a different style to the layer.
virtual bool isModified() const
Returns true if the provider has been modified since the last commit.
bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole) override
@ RenderSymbolPreview
The render is for a symbol preview only and map based properties may not be available,...
QgsLayerTreeNode * parent()
Gets pointer to the parent. If parent is nullptr, the node is a root node.
@ AllowNodeChangeVisibility
Allow user to set node visibility with a checkbox.
void nodeRemovedChildren()
void invalidateLegendMapBasedData()
void willRemoveChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes will be removed from a node within the tree.
@ AllowNodeReorder
Allow reordering with drag'n'drop.
QSize minimumIconSize() const
Calculates the minimum icon size to prevent cropping.
virtual bool isSpatial() const
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
void nodeVisibilityChanged(QgsLayerTreeNode *node)
bool isVisible() const
Returns whether a node is really visible (ie checked and all its ancestors checked as well)
QList< QgsLayerTreeModelLegendNode * > layerLegendNodes(QgsLayerTreeLayer *nodeLayer, bool skipNodeEmbeddedInParent=false)
Returns filtered list of active legend nodes attached to a particular layer node (by default it retur...
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
@ ShowLegend
Add legend nodes for layer nodes.
void nodeNameChanged(QgsLayerTreeNode *node, const QString &name)
Updates model when node's name has changed.
static QString legendFilterByExpression(const QgsLayerTreeLayer &layer, bool *enabled=nullptr)
Returns the expression filter of a legend layer.
QgsLayerTreeModel(QgsLayerTree *rootNode, QObject *parent=nullptr)
Construct a new tree model with given layer tree (root node must not be nullptr).
@ RuleKeyRole
Rule key of the node (QString)
void setExpanded(bool expanded)
Sets whether the node should be shown as expanded or collapsed in GUI.
int legendRootRowCount(QgsLayerTreeLayer *nL) const
QgsWkbTypes::GeometryType type
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
static bool isGroup(QgsLayerTreeNode *node)
Check whether the node is a valid group node.
QgsMapLayerType type() const
Returns the type of the layer.
void refreshScaleBasedLayers(const QModelIndex &index=QModelIndex())
Updates layer data for scale dependent layers, should be called when map scale changes.
void legendInvalidateMapBasedData()
void connectToLayer(QgsLayerTreeLayer *nodeLayer)
void dataChanged()
Emitted on internal data change so the layer tree model can forward the signal to views.
@ UseEmbeddedWidgets
Layer nodes may optionally include extra embedded widgets (if used in QgsLayerTreeView)....
void setCurrentIndex(const QModelIndex ¤tIndex)
Sets index of the current item. May be used by view. Item marked as current is underlined.
QList< QgsLayerTreeNode * > indexes2nodes(const QModelIndexList &list, bool skipInternal=false) const
Convert a list of indexes to a list of layer tree nodes.
void visibilityChanged(QgsLayerTreeNode *node)
Emitted when check state of a node within the tree has been changed.
QList< QgsLayerTreeModelLegendNode * > layerOriginalLegendNodes(QgsLayerTreeLayer *nodeLayer)
Returns original (unfiltered) list of legend nodes attached to a particular layer node.