17 #include <QTextStream> 
   42   : QAbstractItemModel( parent )
 
   43   , mRootNode( rootNode )
 
   44   , mFlags( ShowLegend | AllowLegendChangeState | DeferredLegendInvalidation )
 
   45   , mAutoCollapseLegendNodesCount( -1 )
 
   46   , mLegendFilterByScale( 0 )
 
   47   , mLegendFilterUsesExtent( false )
 
   48   , mLegendMapViewMupp( 0 )
 
   49   , mLegendMapViewDpi( 0 )
 
   50   , mLegendMapViewScale( 0 )
 
   67   if ( !
index.isValid() )
 
   70   QObject *obj = 
reinterpret_cast<QObject *
>( 
index.internalPointer() );
 
   71   return qobject_cast<QgsLayerTreeNode *>( obj );
 
  105     return QModelIndex();
 
  112     return QModelIndex(); 
 
  119   return createIndex( row, column, 
static_cast<QObject *
>( n->
children().at( row ) ) );
 
  125   if ( !child.isValid() )
 
  126     return QModelIndex();
 
  139     return QModelIndex();
 
  147   Q_ASSERT( parentNode );
 
  150   if ( !grandParentNode )
 
  151     return QModelIndex();  
 
  153   int row = grandParentNode->
children().indexOf( parentNode );
 
  154   Q_ASSERT( row >= 0 );
 
  156   return createIndex( row, 0, 
static_cast<QObject *
>( parentNode ) );
 
  169   if ( role == Qt::DisplayRole || role == Qt::EditRole )
 
  177       QString name = nodeLayer->
name();
 
  178       if ( nodeLayer->
customProperty( QStringLiteral( 
"showFeatureCount" ), 0 ).toInt() && role == Qt::DisplayRole )
 
  182           name += QStringLiteral( 
" [%1]" ).arg( vlayer->
featureCount() );
 
  187   else if ( role == Qt::DecorationRole && 
index.column() == 0 )
 
  203       switch ( layer->
type() )
 
  254         QPainter painter( &pixmap );
 
  258         icon = QIcon( pixmap );
 
  264   else if ( role == Qt::CheckStateRole )
 
  288       f.setUnderline( 
true );
 
  294         f.setItalic( !f.italic() );
 
  301     QBrush brush( qApp->palette().color( QPalette::Text ), Qt::SolidPattern );
 
  307         QColor fadedTextColor = brush.color();
 
  308         fadedTextColor.setAlpha( 128 );
 
  309         brush.setColor( fadedTextColor );
 
  314   else if ( role == Qt::ToolTipRole )
 
  321           !layer->
title().isEmpty() ? layer->title() :
 
  322           !layer->shortName().isEmpty() ? layer->shortName() :
 
  325         title = 
"<b>" + title.toHtmlEscaped() + 
"</b>";
 
  327         if ( layer->isSpatial() && layer->crs().isValid() )
 
  329           if ( 
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
 
  332             title += tr( 
" (%1)" ).arg( layer->crs().authid() ).toHtmlEscaped();
 
  338         if ( !layer->abstract().isEmpty() )
 
  341           const QStringList abstractLines = layer->abstract().split( 
'\n' );
 
  342           for ( 
const auto &l : abstractLines )
 
  344             parts << l.toHtmlEscaped();
 
  349         QString source( layer->publicSource() );
 
  350         if ( source.size() > 1024 )
 
  352           source = source.left( 1023 ) + QString( QChar( 0x2026 ) );
 
  355         parts << 
"<i>" + source.toHtmlEscaped() + 
"</i>";
 
  357         return parts.join( QLatin1String( 
"<br/>" ) );
 
  368   if ( !
index.isValid() )
 
  370     Qt::ItemFlags rootFlags = Qt::ItemFlags();
 
  372       rootFlags |= Qt::ItemIsDropEnabled;
 
  379   Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
 
  382     f |= Qt::ItemIsEditable;
 
  385   bool isEmbedded = node->
customProperty( QStringLiteral( 
"embedded" ) ).toInt();
 
  390     if ( !isEmbedded || ( isEmbedded && node->
parent() && !node->
parent()->
customProperty( QStringLiteral( 
"embedded" ) ).toInt() ) )
 
  391       f |= Qt::ItemIsDragEnabled;
 
  395     f |= Qt::ItemIsUserCheckable;
 
  398     f |= Qt::ItemIsDropEnabled;
 
  410     bool res = sym->
setData( value, role );
 
  418     return QAbstractItemModel::setData( 
index, value, role );
 
  420   if ( role == Qt::CheckStateRole )
 
  425     bool checked = 
static_cast< Qt::CheckState 
>( value.toInt() ) == Qt::Checked;
 
  426     if ( checked &&  node->
children().isEmpty() )
 
  446   else if ( role == Qt::EditRole )
 
  454       layer->
setName( value.toString() );
 
  464   return QAbstractItemModel::setData( 
index, value, role );
 
  469   if ( !node || !node->
parent() )
 
  470     return QModelIndex(); 
 
  475   Q_ASSERT( row >= 0 );
 
  476   return index( row, 0, parentIndex );
 
  485   if ( child->
parent() == node )
 
  488   return _isChildOfNode( child->
parent(), node );
 
  491 static bool _isChildOfNodes( 
QgsLayerTreeNode *child, 
const QList<QgsLayerTreeNode *> &nodes )
 
  495     if ( _isChildOfNode( child, n ) )
 
  505   QList<QgsLayerTreeNode *> nodes;
 
  506   const auto constList = list;
 
  507   for ( 
const QModelIndex &
index : constList )
 
  520   QList<QgsLayerTreeNode *> nodesFinal;
 
  523     if ( !_isChildOfNodes( node, nodes ) )
 
  554   emit dataChanged( idx, idx );
 
  558   if ( oldNodeCount > 0 )
 
  560     beginRemoveRows( idx, 0, oldNodeCount - 1 );
 
  647     if ( useExpressions )
 
  654         if ( enabled && !expr.isEmpty() )
 
  656           exprs[ nodeLayer->layerId()] = expr;
 
  661     if ( useExpressions && !useExtent && !polygonValid ) 
 
  706   if ( scale != previousScale )
 
  734   beginInsertRows( 
node2index( node ), indexFrom, indexTo );
 
  737 static QList<QgsLayerTreeLayer *> _layerNodesInSubtree( 
QgsLayerTreeNode *node, 
int indexFrom, 
int indexTo )
 
  739   QList<QgsLayerTreeNode *> children = node->
children();
 
  740   QList<QgsLayerTreeLayer *> newLayerNodes;
 
  741   for ( 
int i = indexFrom; i <= indexTo; ++i )
 
  749   return newLayerNodes;
 
  758   const auto subNodes = _layerNodesInSubtree( node, indexFrom, indexTo );
 
  767   beginRemoveRows( 
node2index( node ), indexFrom, indexTo );
 
  770   const auto subNodes = _layerNodesInSubtree( node, indexFrom, indexTo );
 
  835   QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
 
  851   QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
 
  865   QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
 
  876   if ( nodeLayer->
customProperty( QStringLiteral( 
"showFeatureCount" ) ).toInt() )
 
  888   if ( 
index.isValid() )
 
  892 void QgsLayerTreeModel::legendNodeSizeChanged()
 
  899   if ( 
index.isValid() )
 
  900     emit dataChanged( 
index, 
index, QVector<int> { Qt::SizeHintRole } );
 
  906   if ( !nodeLayer->
layer() )
 
  951   const auto constChildren = group->
children();
 
  969   disconnect( nodeLayer, 
nullptr, 
this, 
nullptr ); 
 
  971   if ( !nodeLayer->
layer() )
 
  982     disconnect( nodeLayer->
layer(), 
nullptr, 
this, 
nullptr );
 
  988   const auto constChildren = parentGroup->
children();
 
 1000   const auto constChildren = parentGroup->
children();
 
 1027   disconnect( 
mRootNode, 
nullptr, 
this, 
nullptr );
 
 1038   int count = node->
children().count();
 
 1041   emit dataChanged( 
index( 0, 0, idx ), 
index( count - 1, 0, idx ) );
 
 1042   for ( 
int i = 0; i < count; ++i )
 
 1058         emit dataChanged( idx, idx, QVector<int>() << Qt::FontRole << Qt::ForegroundRole );
 
 1061   int count = node->
children().count();
 
 1062   for ( 
int i = 0; i < count; ++i )
 
 1068   return Qt::CopyAction | Qt::MoveAction;
 
 1074   types << QStringLiteral( 
"application/qgis.layertreemodeldata" );
 
 1082   QModelIndexList sortedIndexes = indexes;
 
 1083   std::sort( sortedIndexes.begin(), sortedIndexes.end(), std::less<QModelIndex>() );
 
 1085   QList<QgsLayerTreeNode *> nodesFinal = 
indexes2nodes( sortedIndexes, 
true );
 
 1087   if ( nodesFinal.isEmpty() )
 
 1090   QMimeData *
mimeData = 
new QMimeData();
 
 1092   QDomDocument layerTreeDoc;
 
 1093   QDomElement rootLayerTreeElem = layerTreeDoc.createElement( QStringLiteral( 
"layer_tree_model_data" ) );
 
 1099   layerTreeDoc.appendChild( rootLayerTreeElem );
 
 1101   QString errorMessage;
 
 1103   QDomDocument layerDefinitionsDoc( QStringLiteral( 
"qgis-layer-definition" ) );
 
 1106   QString txt = layerDefinitionsDoc.toString();
 
 1108   mimeData->setData( QStringLiteral( 
"application/qgis.layertreemodeldata" ), layerTreeDoc.toString().toUtf8() );
 
 1109   mimeData->setData( QStringLiteral( 
"application/qgis.application.pid" ), QString::number( QCoreApplication::applicationPid() ).toUtf8() );
 
 1110   mimeData->setData( QStringLiteral( 
"application/qgis.layertree.layerdefinitions" ), txt.toUtf8() );
 
 1118   if ( action == Qt::IgnoreAction )
 
 1121   if ( !
data->hasFormat( QStringLiteral( 
"application/qgis.layertreemodeldata" ) ) )
 
 1131   if ( 
parent.isValid() && row == -1 )
 
 1137   qint64 qgisPid = 
data->data( QStringLiteral( 
"application/qgis.application.pid" ) ).toInt( &ok );
 
 1139   if ( ok && qgisPid != QCoreApplication::applicationPid() )
 
 1141     QByteArray encodedLayerDefinitionData = 
data->data( QStringLiteral( 
"application/qgis.layertree.layerdefinitions" ) );
 
 1142     QDomDocument layerDefinitionDoc;
 
 1143     if ( !layerDefinitionDoc.setContent( QString::fromUtf8( encodedLayerDefinitionData ) ) )
 
 1146     QString errorMessage;
 
 1148     emit 
messageEmitted( tr( 
"New layers added from another QGIS instance" ) );
 
 1152     QByteArray encodedLayerTreeData = 
data->data( QStringLiteral( 
"application/qgis.layertreemodeldata" ) );
 
 1154     QDomDocument layerTreeDoc;
 
 1155     if ( !layerTreeDoc.setContent( QString::fromUtf8( encodedLayerTreeData ) ) )
 
 1158     QDomElement rootLayerTreeElem = layerTreeDoc.documentElement();
 
 1159     if ( rootLayerTreeElem.tagName() != QLatin1String( 
"layer_tree_model_data" ) )
 
 1162     QList<QgsLayerTreeNode *> nodes;
 
 1164     QDomElement elem = rootLayerTreeElem.firstChildElement();
 
 1165     while ( !elem.isNull() )
 
 1171       elem = elem.nextSiblingElement();
 
 1174     if ( nodes.isEmpty() )
 
 1213   return mFlags.testFlag( f );
 
 1223   QList<QgsLayerTreeModelLegendNode *> filtered;
 
 1257               if ( 
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( node->layerNode()->layer() ) )
 
 1290   const auto constMLegend = 
mLegend;
 
 1293     qDeleteAll( 
data.originalNodes );
 
 1302   if ( 
mLegend.contains( nodeLayer ) )
 
 1304     qDeleteAll( 
mLegend[nodeLayer].originalNodes );
 
 1305     delete mLegend[nodeLayer].tree;
 
 1313   if ( !nodeL || !nodeL->
layer() )
 
 1333     int widgetsCount = ml->
customProperty( QStringLiteral( 
"embeddedWidgets/count" ), 0 ).toInt();
 
 1334     while ( widgetsCount > 0 )
 
 1336       lstNew.insert( 0, 
new EmbeddedWidgetLegendNode( nodeL ) );
 
 1341   QList<QgsLayerTreeModelLegendNode *> filteredLstNew = 
filterLegendNodes( lstNew );
 
 1343   const auto constLstNew = lstNew;
 
 1346     n->setParent( 
this );
 
 1355   const auto constFilteredLstNew = filteredLstNew;
 
 1372   int count = legendTree ? legendTree->
children[
nullptr].count() : filteredLstNew.count();
 
 1374   if ( !filteredLstNew.isEmpty() )
 
 1377     const QModelIndex nodeIndex { 
node2index( nodeL ) };
 
 1384     beginInsertRows( 
node2index( nodeL ), 0, count - 1 );
 
 1388   data.originalNodes = lstNew;
 
 1389   data.activeNodes = filteredLstNew;
 
 1390   data.embeddedNodeInParent = embeddedNode;
 
 1391   data.tree = legendTree;
 
 1395   if ( !filteredLstNew.isEmpty() )
 
 1410   bool hasParentKeys = 
false;
 
 1415       hasParentKeys = 
true;
 
 1419   if ( !hasParentKeys )
 
 1423   QHash<QString, QgsLayerTreeModelLegendNode *> rule2node;
 
 1424   rule2node[QString()] = 
nullptr;
 
 1428     if ( ruleKey.isEmpty() ) 
 
 1430     if ( rule2node.contains( ruleKey ) ) 
 
 1432     rule2node[ruleKey] = n;
 
 1457   context->setScaleFactor( dpi / 25.4 );
 
 1458   context->setRendererScale( scale );
 
 1461   return validData ? context.release() : 
nullptr;
 
 1467   return qobject_cast<QgsLayerTreeModelLegendNode *>( 
reinterpret_cast<QObject *
>( 
index.internalPointer() ) );
 
 1479       int row = 
data.tree->children[parentLegendNode].indexOf( 
legendNode );
 
 1480       return index( row, 0, parentIndex );
 
 1486       return index( row, 0, parentIndex );
 
 1491   Q_ASSERT( parentIndex.isValid() );
 
 1494     return QModelIndex();
 
 1496   return index( row, 0, parentIndex );
 
 1504     return data.tree->children[node].count();
 
 1512   if ( !
mLegend.contains( nL ) )
 
 1517     return data.tree->children[
nullptr].count();
 
 1519   int count = 
data.activeNodes.count();
 
 1526   Q_ASSERT( 
mLegend.contains( nL ) );
 
 1529     return createIndex( row, column, 
static_cast<QObject *
>( 
data.tree->children[
nullptr].at( row ) ) );
 
 1531   return createIndex( row, column, 
static_cast<QObject *
>( 
data.activeNodes.at( row ) ) );
 
 1539     return createIndex( row, column, 
static_cast<QObject *
>( 
data.tree->children[node].at( row ) ) );
 
 1541   return QModelIndex(); 
 
 1554       int row = 
data.tree->children[grandParentNode].indexOf( parentNode );
 
 1555       return createIndex( row, 0, 
static_cast<QObject *
>( parentNode ) );
 
 1569   return node->
data( role );
 
 1575   Qt::ItemFlags f = node->
flags();
 
 1577     f &= ~Qt::ItemIsUserCheckable;
 
 1584   return static_cast< bool >( 
mLegend[nodeLayer].embeddedNodeInParent );
 
 1589   return mLegend[nodeLayer].embeddedNodeInParent;
 
 1598   return QIcon( qvariant_cast<QPixmap>( 
legendNode->
data( Qt::DecorationRole ) ) );
 
 1604   if ( !
mLegend.contains( nodeLayer ) )
 
 1605     return QList<QgsLayerTreeModelLegendNode *>();
 
 1608   QList<QgsLayerTreeModelLegendNode *> lst( 
data.activeNodes );
 
 1609   if ( !skipNodeEmbeddedInParent && 
data.embeddedNodeInParent )
 
 1610     lst.prepend( 
data.embeddedNodeInParent );
 
 1616   return mLegend.value( nodeLayer ).originalNodes;
 
 1621   for ( 
auto it = 
mLegend.constBegin(); it != 
mLegend.constEnd(); ++it )
 
 1624     if ( layer->
layerId() == layerId )
 
 1626       const auto activeNodes = 
mLegend.value( layer ).activeNodes;
 
 1659   std::unique_ptr<QgsRenderContext> context( createTemporaryRenderContext() );
 
 1665     QList<QgsSymbolLegendNode *> symbolNodes;
 
 1666     QMap<QString, int> widthMax;
 
 1674         widthMax[parentKey] = std::max( sz.width(), widthMax.contains( parentKey ) ? widthMax[parentKey] : 0 );
 
 1676         symbolNodes.append( n );
 
 1682       Q_ASSERT( widthMax[parentKey] > 0 );
 
 1683       const int twiceMarginWidth = 2; 
 
 1684       n->setIconSize( QSize( widthMax[parentKey] + twiceMarginWidth, n->iconSize().rheight() + twiceMarginWidth ) );
 
static int scaleIconSize(int standardSize, bool applyDevicePixelRatio=false)
Scales an icon size to compensate for display pixel density, making the icon size hi-dpi friendly,...
static QPixmap getThemePixmap(const QString &name, const QColor &foreColor=QColor(), const QColor &backColor=QColor(), int size=16)
Helper to get a theme icon as a pixmap.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
A geometry is the spatial representation of a feature.
QgsWkbTypes::GeometryType type
static QIcon iconLine()
Returns an icon representing line geometries.
static QIcon iconPolygon()
Returns an icon representing polygon geometries.
static QIcon iconDefaultLayer()
Returns a default icon for layers, which aren't the standard raster/vector/...
static QIcon iconPointCloud()
Returns an icon representing point cloud layers.
static QIcon iconPoint()
Returns an icon representing point geometries.
static QIcon iconTable()
Returns an icon representing non-spatial layers (tables).
static QIcon iconRaster()
Returns an icon representing raster layers.
static QIcon iconMesh()
Returns an icon representing mesh layers.
static QIcon iconVectorTile()
Returns an icon representing vector tile layers.
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...
static bool exportLayerDefinition(QString path, const QList< QgsLayerTreeNode * > &selectedTreeNodes, QString &errorMessage)
Export the selected layer tree nodes to a QLR file.
Layer tree group node serves as a container for layers and further groups.
void setName(const QString &n) override
Sets the group's name.
QString name() const override
Returns the group's name.
void insertChildNodes(int index, const QList< QgsLayerTreeNode * > &nodes)
Insert existing nodes at specified position.
QList< QgsLayerTreeLayer * > findLayers() const
Find all layer nodes.
QgsLayerTreeLayer * findLayer(QgsMapLayer *layer) const
Find layer node representing the map layer.
void removeChildren(int from, int count)
Remove child nodes from index "from".
Layer tree node points to a map layer.
QString layerId() const
Returns the ID for the map layer associated with this node.
void layerWillBeUnloaded()
Emitted when a previously available layer got unloaded (from layer registry).
void setName(const QString &n) override
Sets the layer's name.
QString name() const override
Returns the layer's name.
void layerLoaded()
Emitted when a previously unavailable layer got loaded.
QgsMapLayer * layer() const
Returns the map layer associated with this node.
The QgsLegendRendererItem class is abstract interface for legend items returned from QgsMapLayerLegen...
virtual QVariant data(int role) const =0
Returns data associated with the item. Must be implemented in derived class.
NodeTypes
Types of legend nodes.
@ SimpleLegend
Simple label with icon legend node type.
@ RasterSymbolLegend
Raster symbol legend node type.
@ ImageLegend
Raster image legend node type.
@ DataDefinedSizeLegend
Marker symbol legend node type.
@ WmsLegend
WMS legend node type.
@ EmbeddedWidget
Embedded widget placeholder node type.
@ ColorRampLegend
Color ramp legend (since QGIS 3.18)
@ SymbolLegend
Vector symbol legend node type.
QgsLayerTreeLayer * layerNode() const
Returns pointer to the parent layer node.
virtual void invalidateMapBasedData()
Notification from model that information from associated map view has changed.
@ ParentRuleKeyRole
Rule key of the parent legend node - for legends with tree hierarchy (QString). Added in 2....
@ RuleKeyRole
Rule key of the node (QString)
@ NodeTypeRole
Type of node. Added in 3.16.
void sizeChanged()
Emitted when the size of this node changes.
void dataChanged()
Emitted on internal data change so the layer tree model can forward the signal to views.
virtual bool isEmbeddedInParent() const
virtual Qt::ItemFlags flags() const
Returns item flags associated with the item. Default implementation returns Qt::ItemIsEnabled.
virtual bool setData(const QVariant &value, int role)
Sets some data associated with the item. Default implementation does nothing and returns false.
QTimer mDeferLegendInvalidationTimer
void legendInvalidateMapBasedData()
void connectToLayer(QgsLayerTreeLayer *nodeLayer)
int columnCount(const QModelIndex &parent=QModelIndex()) const override
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...
Flags flags() const
Returns OR-ed combination of model flags.
double mLegendFilterByScale
scale denominator for filtering of legend nodes (<= 0 means no filtering)
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...
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override
bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole) override
int autoCollapseLegendNodes() const
Returns at what number of legend nodes the layer node should be collapsed. -1 means no auto-collapse ...
void nodeLayerWillBeUnloaded()
QVariant legendNodeData(QgsLayerTreeModelLegendNode *node, int role) const
double mLegendMapViewScale
void setRootGroup(QgsLayerTree *newRootGroup)
Reset the model and use a new root group node.
void setLegendFilterByMap(const QgsMapSettings *settings)
Force only display of legend nodes which are valid for given map settings.
QModelIndex legendNode2index(QgsLayerTreeModelLegendNode *legendNode)
Returns index for a given legend node.
void setLegendFilterByScale(double scale)
Force only display of legend nodes which are valid for a given scale.
~QgsLayerTreeModel() override
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
std::unique_ptr< QgsMapSettings > mLegendFilterMapSettings
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...
void nodeCustomPropertyChanged(QgsLayerTreeNode *node, const QString &key)
QgsLayerTreeModel(QgsLayerTree *rootNode, QObject *parent=nullptr)
Construct a new tree model with given layer tree (root node must not be nullptr).
void connectToLayers(QgsLayerTreeGroup *parentGroup)
std::unique_ptr< QgsMapHitTest > mLegendFilterHitTest
QModelIndex parent(const QModelIndex &child) const override
bool mLegendFilterUsesExtent
whether to use map filtering
void setFlag(Flag f, bool on=true)
Enable or disable a model flag.
QModelIndex legendParent(QgsLayerTreeModelLegendNode *legendNode) const
void setLayerTreeNodeFont(int nodeType, const QFont &font)
Sets font for a particular type of layer tree node. nodeType should come from QgsLayerTreeNode::NodeT...
int legendNodeRowCount(QgsLayerTreeModelLegendNode *node) const
void nodeAddedChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
void setAutoCollapseLegendNodes(int nodeCount)
Sets at what number of legend nodes the layer node should be collapsed. Setting -1 disables the auto-...
void legendMapViewData(double *mapUnitsPerPixel, int *dpi, double *scale) const
Gets hints about map view - to be used in legend nodes.
QModelIndex currentIndex() const
Gets index of the item marked as current. Item marked as current is underlined.
void recursivelyEmitDataChanged(const QModelIndex &index=QModelIndex())
emit dataChanged() for layer tree node items
bool legendEmbeddedInParent(QgsLayerTreeLayer *nodeLayer) const
QHash< QgsLayerTreeLayer *, LayerLegendData > mLegend
Per layer data about layer's legend nodes.
void disconnectFromLayer(QgsLayerTreeLayer *nodeLayer)
void setCurrentIndex(const QModelIndex ¤tIndex)
Sets index of the current item. May be used by view. Item marked as current is underlined.
QIcon legendIconEmbeddedInParent(QgsLayerTreeLayer *nodeLayer) const
void layerFlagsChanged()
Emitted when layer flags have changed.
void nodeNameChanged(QgsLayerTreeNode *node, const QString &name)
Updates model when node's name has changed.
QPersistentModelIndex mCurrentIndex
Current index - will be underlined.
LayerLegendTree * tryBuildLegendTree(const QList< QgsLayerTreeModelLegendNode * > &nodes)
Qt::DropActions supportedDropActions() const override
void disconnectFromRootNode()
QModelIndex legendNodeIndex(int row, int column, QgsLayerTreeModelLegendNode *node) const
void invalidateLegendMapBasedData()
void setFlags(QgsLayerTreeModel::Flags f)
Sets OR-ed combination of model flags.
QgsLayerTree * rootGroup() const
Returns pointer to the root node of the layer tree. Always a non nullptr value.
void nodeWillRemoveChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
QgsLayerTreeNode * index2node(const QModelIndex &index) const
Returns layer tree node for given index.
QgsLayerTree * mRootNode
Pointer to the root node of the layer tree. Not owned by the model.
QStringList mimeTypes() const override
QMimeData * mimeData(const QModelIndexList &indexes) const override
void nodeRemovedChildren()
int rowCount(const QModelIndex &parent=QModelIndex()) const override
bool removeRows(int row, int count, const QModelIndex &parent=QModelIndex()) override
static int scaleIconSize(int standardSize)
Scales an layer tree model icon size to compensate for display pixel density, making the icon size hi...
void messageEmitted(const QString &message, Qgis::MessageLevel level=Qgis::MessageLevel::Info, int duration=5)
Emits a message than can be displayed to the user in a GUI class.
QgsLayerTreeModelLegendNode * legendNodeEmbeddedInParent(QgsLayerTreeLayer *nodeLayer) const
Returns legend node that may be embedded in parent (i.e.
QList< QgsLayerTreeNode * > indexes2nodes(const QModelIndexList &list, bool skipInternal=false) const
Convert a list of indexes to a list of layer tree nodes.
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
QList< QgsLayerTreeModelLegendNode * > filterLegendNodes(const QList< QgsLayerTreeModelLegendNode * > &nodes)
Filter nodes from QgsMapLayerLegend according to the current filtering rules.
QList< QgsLayerTreeModelLegendNode * > layerOriginalLegendNodes(QgsLayerTreeLayer *nodeLayer)
Returns original (unfiltered) list of legend nodes attached to a particular layer node.
int mAutoCollapseLegendNodesCount
Minimal number of nodes when legend should be automatically collapsed. -1 = disabled.
QMap< QString, QString > layerStyleOverrides() const
Gets map of map layer style overrides (key: layer ID, value: style name) where a different style shou...
Qt::ItemFlags legendNodeFlags(QgsLayerTreeModelLegendNode *node) const
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...
void nodeVisibilityChanged(QgsLayerTreeNode *node)
void refreshScaleBasedLayers(const QModelIndex &index=QModelIndex(), double previousScale=0.0)
Updates layer data for scale dependent layers, should be called when map scale changes.
void removeLegendFromLayer(QgsLayerTreeLayer *nodeLayer)
QModelIndex legendRootIndex(int row, int column, QgsLayerTreeLayer *nL) const
static QgsLayerTreeModelLegendNode * index2legendNode(const QModelIndex &index)
Returns legend node for given index.
double mLegendMapViewMupp
void legendNodeDataChanged()
QMap< QString, QString > mLayerStyleOverrides
Overrides of map layers' styles: key = layer ID, value = style XML.
void nodeWillAddChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
QFont layerTreeNodeFont(int nodeType) const
Gets font for a particular type of layer tree node. nodeType should come from QgsLayerTreeNode::NodeT...
void refreshLayerLegend(QgsLayerTreeLayer *nodeLayer)
Force a refresh of legend nodes of a layer node.
void addLegendToLayer(QgsLayerTreeLayer *nodeL)
bool testFlag(Flag f) const
Check whether a flag is enabled.
void disconnectFromLayers(QgsLayerTreeGroup *parentGroup)
void layerLegendChanged()
QModelIndex indexOfParentLayerTreeNode(QgsLayerTreeNode *parentNode) const
QSet< QgsLayerTreeLayer * > mInvalidatedNodes
Keep track of layer nodes for which the legend size needs to be recalculated.
@ ActionHierarchical
Check/uncheck action has consequences on children (or parents for leaf node)
@ AllowNodeChangeVisibility
Allow user to set node visibility with a checkbox.
@ ShowLegendAsTree
For legends that support it, will show them in a tree instead of a list (needs also ShowLegend)....
@ UseTextFormatting
Layer nodes will alter text appearance based on layer properties, such as scale based visibility.
@ AllowNodeReorder
Allow reordering with drag'n'drop.
@ ShowLegend
Add legend nodes for layer nodes.
@ DeferredLegendInvalidation
Defer legend model invalidation.
@ AllowNodeRename
Allow renaming of groups and layers.
@ AllowLegendChangeState
Allow check boxes for legend nodes (if supported by layer's legend)
@ UseEmbeddedWidgets
Layer nodes may optionally include extra embedded widgets (if used in QgsLayerTreeView)....
Flags mFlags
Sets of flags for the model.
void setLegendFilter(const QgsMapSettings *settings, bool useExtent=true, const QgsGeometry &polygon=QgsGeometry(), bool useExpressions=true)
Filter display of legend nodes for given map settings.
int legendRootRowCount(QgsLayerTreeLayer *nL) const
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.
This class is a base class for nodes in a layer tree.
@ NodeGroup
Container of other groups and layers.
@ NodeLayer
Leaf node pointing to a layer.
void removedChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes has been removed from a node within the tree.
void nameChanged(QgsLayerTreeNode *node, QString name)
Emitted when the name of the node is changed.
bool isVisible() const
Returns whether a node is really visible (ie checked and all its ancestors checked as well)
virtual void writeXml(QDomElement &parentElement, const QgsReadWriteContext &context)=0
Write layer tree to XML.
static QgsLayerTreeNode * readXml(QDomElement &element, const QgsReadWriteContext &context)
Read layer tree from XML.
void willRemoveChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes will be removed from a node within the tree.
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.
void setExpanded(bool expanded)
Sets whether the node should be shown as expanded or collapsed in GUI.
NodeType nodeType() const
Find out about type of the node. It is usually shorter to use convenience functions from QgsLayerTree...
void customPropertyChanged(QgsLayerTreeNode *node, const QString &key)
Emitted when a custom property of a node within the tree has been changed or removed.
QgsLayerTreeNode * parent()
Gets pointer to the parent. If parent is nullptr, the node is a root node.
void addedChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes have been added to a node within the tree.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
void willAddChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes will be added to a node within the tree.
void visibilityChanged(QgsLayerTreeNode *node)
Emitted when check state of a node within the tree has been changed.
virtual void setItemVisibilityCheckedRecursive(bool checked)
Check or uncheck a node and all its children (taking into account exclusion rules)
void setItemVisibilityChecked(bool checked)
Check or uncheck a node (independently of its ancestors or children)
bool itemVisibilityChecked() const
Returns whether a node is checked (independently of its ancestors or children)
void setItemVisibilityCheckedParentRecursive(bool checked)
Check or uncheck a node and all its parents.
static QString legendFilterByExpression(const QgsLayerTreeLayer &layer, bool *enabled=nullptr)
Returns the expression filter of a legend layer.
Namespace with helper functions for layer tree operations.
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
static bool isGroup(QgsLayerTreeNode *node)
Check whether the node is a valid group node.
static QgsLayerTreeGroup * toGroup(QgsLayerTreeNode *node)
Cast node to a group.
Class that runs a hit test with given map settings.
QMap< QString, QString > LayerFilterExpression
Maps an expression string to a layer id.
static void applyLayerNodeProperties(QgsLayerTreeLayer *nodeLayer, QList< QgsLayerTreeModelLegendNode * > &nodes)
update according to layer node's custom properties (order of items, user labels for items)
The QgsMapLayerLegend class is abstract interface for implementations of legends for one map layer.
virtual QList< QgsLayerTreeModelLegendNode * > createLayerTreeModelLegendNodes(QgsLayerTreeLayer *nodeLayer)=0
Returns list of legend nodes to be used for a particular layer tree layer node.
Restore overridden layer style on destruction.
void setOverrideStyle(const QString &style)
Temporarily apply a different style to the layer.
Base class for all map layer types.
virtual bool isSpatial() const
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
bool isInScaleRange(double scale) const
Tests whether the layer should be visible at the specified scale.
void legendChanged()
Signal emitted when legend of the layer has changed.
QgsMapLayerLegend * legend() const
Can be nullptr.
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
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.
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
void flagsChanged()
Emitted when layer's flags have been modified.
The QgsMapSettings class contains configuration for rendering of the map.
bool hasValidSettings() const
Check whether the map settings are valid and can be used for rendering.
Perform transforms between map coordinates and device coordinates.
static QByteArray layerTreeNodesToUriList(const QList< QgsLayerTreeNode * > &nodes)
Returns encoded URI list from a list of layer tree nodes.
static QgsProject * instance()
Returns the QgsProject singleton instance.
The class is used as a container of context for various read/write operations on other objects.
Contains information about the context of a rendering operation.
@ RenderSymbolPreview
The render is for a symbol preview only and map based properties may not be available,...
Implementation of legend node interface for displaying preview of vector symbols and their labels and...
void setIconSize(QSize sz)
Set the icon size.
QSize minimumIconSize() const
Calculates the minimum icon size to prevent cropping.
QVariant data(int role) const override
Returns data associated with the item. Must be implemented in derived class.
Represents a vector layer which manages a vector based data sets.
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
void editingStopped()
Emitted when edited changes have been successfully written to the data provider.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
virtual bool isModified() const
Returns true if the provider has been modified since the last commit.
void editingStarted()
Emitted when editing on this layer has started.
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
void layerModified()
Emitted when modifications has been done on layer.
static QString displayString(Type type) SIP_HOLDGIL
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
@ PointCloudLayer
Added in 3.18.
@ VectorTileLayer
Added in 3.14.
@ AnnotationLayer
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
QSize iconSize(bool dockableToolbar)
Returns the user-preferred size of a window's toolbar icons.
QgsLayerTreeModelLegendNode * legendNode(const QString &rule, QgsLayerTreeModel &model)
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
#define QgsDebugMsgLevel(str, level)
Structure that stores all data associated with one map layer.
Structure that stores tree representation of map layer's legend.
QMap< QgsLayerTreeModelLegendNode *, QgsLayerTreeModelLegendNode * > parents
Pointer to parent for each active node. Top-level nodes have nullptr parent. Pointers are not owned.
QMap< QgsLayerTreeModelLegendNode *, QList< QgsLayerTreeModelLegendNode * > > children
List of children for each active node. Top-level nodes are under nullptr key. Pointers are not owned.