42#include "moc_qgslayertreemodel.cpp"
44using namespace Qt::StringLiterals;
47 : QAbstractItemModel(
parent )
69 if ( !
index.isValid() )
72 QObject *obj =
reinterpret_cast<QObject *
>(
index.internalPointer() );
73 return qobject_cast<QgsLayerTreeNode *>( obj );
106 return QModelIndex();
113 return QModelIndex();
120 return createIndex( row, column,
static_cast<QObject *
>( n->
children().at( row ) ) );
126 if ( !child.isValid() )
127 return QModelIndex();
140 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();
179 if ( vlayer && nodeLayer->
customProperty( u
"showFeatureCount"_s, 0 ).toInt() && role == Qt::DisplayRole )
185 name += u
" [%1%2]"_s.arg( estimatedCount ? u
"≈"_s : QString(), count != -1 ? QLocale().toString( count ) : tr(
"N/A" ) );
195 else if ( role == Qt::DecorationRole &&
index.column() == 0 )
220 QPixmap pixmap( icon.pixmap( iconSize, iconSize ) );
222 QPainter painter( &pixmap );
226 icon = QIcon( pixmap );
232 else if ( role == Qt::CheckStateRole )
260 f.setUnderline(
true );
266 f.setItalic( !f.italic() );
273 QBrush brush( qApp->palette().color( QPalette::Text ), Qt::SolidPattern );
279 QColor fadedTextColor = brush.color();
280 fadedTextColor.setAlpha( 128 );
281 brush.setColor( fadedTextColor );
286 else if ( role == Qt::ToolTipRole )
292 QString title = !layer->metadata().title().isEmpty() ? layer->metadata().title()
293 : !layer->serverProperties()->title().isEmpty() ? layer->serverProperties()->title()
294 : !layer->serverProperties()->shortName().isEmpty() ? layer->serverProperties()->shortName()
297 title =
"<b>" + title.toHtmlEscaped() +
"</b>";
299 if ( layer->isSpatial() && layer->crs().isValid() )
301 QString layerCrs = layer->crs().authid();
302 if ( !std::isnan( layer->crs().coordinateEpoch() ) )
304 layerCrs += u
" @ %1"_s.arg(
qgsDoubleToString( layer->crs().coordinateEpoch(), 3 ) );
306 if (
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
309 title += tr(
" (%1)" ).arg( layerCrs ).toHtmlEscaped();
315 const QString abstract = !layer->metadata().abstract().isEmpty() ? layer->metadata().abstract() : layer->serverProperties()->abstract();
316 if ( !abstract.isEmpty() )
319 const QStringList abstractLines = abstract.split(
'\n' );
320 for (
const auto &l : abstractLines )
322 parts << l.toHtmlEscaped();
327 QString source( layer->publicSource() );
328 if ( source.size() > 1024 )
330 source = source.left( 1023 ) + QString( QChar( 0x2026 ) );
333 parts <<
"<i>" + source.toHtmlEscaped() +
"</i>";
336 const bool showFeatureCount = nodeLayer->
customProperty( u
"showFeatureCount"_s, 0 ).toBool();
338 if ( showFeatureCount && estimatedCount )
340 parts << tr(
"<b>Feature count is estimated</b> : the feature count is determined by the database statistics" );
345 parts << tr(
"ID: %1" ).arg( layer->id() );
348 return parts.join(
"<br/>"_L1 );
359 if ( !
index.isValid() )
361 Qt::ItemFlags rootFlags = Qt::ItemFlags();
363 rootFlags |= Qt::ItemIsDropEnabled;
370 Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
373 f |= Qt::ItemIsEditable;
382 f |= Qt::ItemIsDragEnabled;
386 f |= Qt::ItemIsUserCheckable;
389 f |= Qt::ItemIsDropEnabled;
401 bool res = sym->
setData( value, role );
409 return QAbstractItemModel::setData(
index, value, role );
411 if ( role == Qt::CheckStateRole )
416 bool checked =
static_cast< Qt::CheckState
>( value.toInt() ) == Qt::Checked;
417 if ( checked && node->
children().isEmpty() )
437 else if ( role == Qt::EditRole )
445 layer->
setName( value.toString() );
460 return QAbstractItemModel::setData(
index, value, role );
465 if ( !node || !node->
parent() )
466 return QModelIndex();
471 Q_ASSERT( row >= 0 );
472 return index( row, 0, parentIndex );
481 if ( child->
parent() == node )
484 return _isChildOfNode( child->
parent(), node );
487static bool _isChildOfNodes(
QgsLayerTreeNode *child,
const QList<QgsLayerTreeNode *> &nodes )
491 if ( _isChildOfNode( child, n ) )
501 QList<QgsLayerTreeNode *> nodes;
502 const auto constList = list;
503 for (
const QModelIndex &
index : constList )
516 QList<QgsLayerTreeNode *> nodesFinal;
519 if ( !_isChildOfNodes( node, nodes ) )
550 emit dataChanged( idx, idx );
554 if ( oldNodeCount > 0 )
556 beginRemoveRows( idx, 0, oldNodeCount - 1 );
624 const auto layers =
mRootNode->findLayers();
640 auto filterSettings = std::make_unique< QgsLayerTreeFilterSettings >( *settings );
651 if ( useExpressions )
673 mFilterSettings = std::make_unique< QgsLayerTreeFilterSettings >( *settings );
676 bool hitTestWasRunning =
false;
683 hitTestWasRunning =
true;
692 if ( !hitTestWasRunning )
697 auto blockingHitTest = std::make_unique< QgsMapHitTest >( *
mFilterSettings );
698 blockingHitTest->run();
701 handleHitTestResults();
710 handleHitTestResults();
719void QgsLayerTreeModel::handleHitTestResults()
740 const QList<QgsLayerTreeModelLegendNode *> legendNodes =
layerLegendNodes( layerTreeLayer );
750 colorRampNode->setMinimum( limits.first );
751 colorRampNode->setMaximum( limits.second );
772 if ( scale != previousScale )
778 if ( mapUnitsPerPixel )
827 beginInsertRows(
node2index( node ), indexFrom, indexTo );
830static QList<QgsLayerTreeLayer *> _layerNodesInSubtree(
QgsLayerTreeNode *node,
int indexFrom,
int indexTo )
832 QList<QgsLayerTreeNode *> children = node->
children();
833 QList<QgsLayerTreeLayer *> newLayerNodes;
834 for (
int i = indexFrom; i <= indexTo; ++i )
842 return newLayerNodes;
851 const auto subNodes = _layerNodesInSubtree( node, indexFrom, indexTo );
860 beginRemoveRows(
node2index( node ), indexFrom, indexTo );
863 const auto subNodes = _layerNodesInSubtree( node, indexFrom, indexTo );
928 QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
944 QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
958 QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
981 if (
index.isValid() )
985void QgsLayerTreeModel::legendNodeSizeChanged()
992 if (
index.isValid() )
993 emit dataChanged(
index,
index, QVector<int> { Qt::SizeHintRole } );
996void QgsLayerTreeModel::hitTestTaskCompleted()
1003 handleHitTestResults();
1010 if ( !nodeLayer->
layer() )
1026 if ( !
mRootNode->customProperty( u
"loading"_s ).toBool() )
1062 const auto constChildren = group->
children();
1080 disconnect( nodeLayer,
nullptr,
this,
nullptr );
1082 if ( !nodeLayer->
layer() )
1093 disconnect( nodeLayer->
layer(),
nullptr,
this,
nullptr );
1099 const auto constChildren = parentGroup->
children();
1111 const auto constChildren = parentGroup->
children();
1140 disconnect(
mRootNode,
nullptr,
this,
nullptr );
1151 int count = node->
children().count();
1154 emit dataChanged(
index( 0, 0, idx ),
index( count - 1, 0, idx ) );
1155 for (
int i = 0; i < count; ++i )
1171 emit dataChanged( idx, idx, QVector<int>() << Qt::FontRole << Qt::ForegroundRole );
1174 int count = node->
children().count();
1175 for (
int i = 0; i < count; ++i )
1181 return Qt::CopyAction | Qt::MoveAction;
1187 types << u
"application/qgis.layertreemodeldata"_s;
1195 QModelIndexList sortedIndexes = indexes;
1196 std::sort( sortedIndexes.begin(), sortedIndexes.end(), std::less<QModelIndex>() );
1198 QList<QgsLayerTreeNode *> nodesFinal =
indexes2nodes( sortedIndexes,
true );
1200 if ( nodesFinal.isEmpty() )
1203 QMimeData *
mimeData =
new QMimeData();
1205 QDomDocument layerTreeDoc;
1206 QDomElement rootLayerTreeElem = layerTreeDoc.createElement( u
"layer_tree_model_data"_s );
1212 layerTreeDoc.appendChild( rootLayerTreeElem );
1214 QString errorMessage;
1216 QDomDocument layerDefinitionsDoc( u
"qgis-layer-definition"_s );
1219 QString txt = layerDefinitionsDoc.toString();
1221 mimeData->setData( u
"application/qgis.layertreemodeldata"_s, layerTreeDoc.toString().toUtf8() );
1222 mimeData->setData( u
"application/qgis.application.pid"_s, QString::number( QCoreApplication::applicationPid() ).toUtf8() );
1223 mimeData->setData( u
"application/qgis.layertree.source"_s, u
":0x%1"_s.arg(
reinterpret_cast<quintptr
>(
this ), 2 * QT_POINTER_SIZE, 16,
'0'_L1 ).toUtf8() );
1224 mimeData->setData( u
"application/qgis.layertree.layerdefinitions"_s, txt.toUtf8() );
1232 if ( action == Qt::IgnoreAction )
1235 if ( !
data->hasFormat( u
"application/qgis.layertreemodeldata"_s ) )
1242 const QString restrictTypes(
data->data( u
"application/qgis.restrictlayertreemodelsubclass"_s ) );
1243 if ( !restrictTypes.isEmpty() && restrictTypes != QString( metaObject()->className() ) )
1250 if (
parent.isValid() && row == -1 )
1256 qint64 qgisPid =
data->data( u
"application/qgis.application.pid"_s ).toInt( &ok );
1258 if ( ok && qgisPid != QCoreApplication::applicationPid() )
1260 QByteArray encodedLayerDefinitionData =
data->data( u
"application/qgis.layertree.layerdefinitions"_s );
1261 QDomDocument layerDefinitionDoc;
1262 if ( !layerDefinitionDoc.setContent( QString::fromUtf8( encodedLayerDefinitionData ) ) )
1265 QString errorMessage;
1267 emit
messageEmitted( tr(
"New layers added from another QGIS instance" ) );
1271 QByteArray encodedLayerTreeData =
data->data( u
"application/qgis.layertreemodeldata"_s );
1273 QDomDocument layerTreeDoc;
1274 if ( !layerTreeDoc.setContent( QString::fromUtf8( encodedLayerTreeData ) ) )
1277 QDomElement rootLayerTreeElem = layerTreeDoc.documentElement();
1278 if ( rootLayerTreeElem.tagName() !=
"layer_tree_model_data"_L1 )
1281 QList<QgsLayerTreeNode *> nodes;
1283 QDomElement elem = rootLayerTreeElem.firstChildElement();
1284 while ( !elem.isNull() )
1290 elem = elem.nextSiblingElement();
1293 if ( nodes.isEmpty() )
1332 return mFlags.testFlag( f );
1342 QList<QgsLayerTreeModelLegendNode *> filtered;
1354 if ( !nodes.isEmpty() &&
mFilterSettings->layers().contains( nodes.at( 0 )->layerNode()->layer() ) )
1379 if (
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( node->layerNode()->layer() ) )
1382 if ( it !=
mHitTestResults.constEnd() && ( it->contains( ruleKey ) || ( !it->isEmpty() && isDataDefinedSize ) ) )
1414 const auto constMLegend =
mLegend;
1417 qDeleteAll(
data.originalNodes );
1434 if (
mLegend.contains( nodeLayer ) )
1436 qDeleteAll(
mLegend[nodeLayer].originalNodes );
1437 delete mLegend[nodeLayer].tree;
1445 if ( !nodeL || !nodeL->
layer() )
1465 int widgetsCount = ml->
customProperty( u
"embeddedWidgets/count"_s, 0 ).toInt();
1466 while ( widgetsCount > 0 )
1468 lstNew.insert( 0,
new EmbeddedWidgetLegendNode( nodeL ) );
1473 QList<QgsLayerTreeModelLegendNode *> filteredLstNew =
filterLegendNodes( lstNew );
1475 const auto constLstNew = lstNew;
1478 n->setParent(
this );
1487 const auto constFilteredLstNew = filteredLstNew;
1492 embeddedNode = legendNode;
1493 filteredLstNew.removeOne( legendNode );
1504 int count = legendTree ? legendTree->
children[
nullptr].count() : filteredLstNew.count();
1506 if ( !filteredLstNew.isEmpty() )
1509 const QModelIndex nodeIndex {
node2index( nodeL ) };
1516 beginInsertRows(
node2index( nodeL ), 0, count - 1 );
1520 data.originalNodes = lstNew;
1521 data.activeNodes = filteredLstNew;
1522 data.embeddedNodeInParent = embeddedNode;
1523 data.tree = legendTree;
1527 if ( !filteredLstNew.isEmpty() )
1542 bool hasParentKeys =
false;
1547 hasParentKeys =
true;
1551 if ( !hasParentKeys )
1555 QHash<QString, QgsLayerTreeModelLegendNode *> rule2node;
1556 rule2node[QString()] =
nullptr;
1560 if ( ruleKey.isEmpty() )
1562 if ( rule2node.contains( ruleKey ) )
1564 rule2node[ruleKey] = n;
1589 context->setScaleFactor( dpi / 25.4 );
1596 context->setRendererScale( scale );
1601 return validData ? context.release() :
nullptr;
1606 return qobject_cast<QgsLayerTreeModelLegendNode *>(
reinterpret_cast<QObject *
>(
index.internalPointer() ) );
1618 int row =
data.tree->children[parentLegendNode].indexOf( legendNode );
1619 return index( row, 0, parentIndex );
1624 int row =
data.tree->children[
nullptr].indexOf( legendNode );
1625 return index( row, 0, parentIndex );
1630 Q_ASSERT( parentIndex.isValid() );
1631 int row =
data.activeNodes.indexOf( legendNode );
1633 return QModelIndex();
1635 return index( row, 0, parentIndex );
1643 return data.tree->children[node].count();
1651 if ( !
mLegend.contains( nL ) )
1656 return data.tree->children[
nullptr].count();
1658 int count =
data.activeNodes.count();
1665 Q_ASSERT(
mLegend.contains( nL ) );
1668 return createIndex( row, column,
static_cast<QObject *
>(
data.tree->children[
nullptr].at( row ) ) );
1670 return createIndex( row, column,
static_cast<QObject *
>(
data.activeNodes.at( row ) ) );
1678 return createIndex( row, column,
static_cast<QObject *
>(
data.tree->children[node].at( row ) ) );
1680 return QModelIndex();
1693 int row =
data.tree->children[grandParentNode].indexOf( parentNode );
1694 return createIndex( row, 0,
static_cast<QObject *
>( parentNode ) );
1708 return node->
data( role );
1714 Qt::ItemFlags f = node->
flags();
1716 f &= ~Qt::ItemIsUserCheckable;
1723 return static_cast< bool >(
mLegend[nodeLayer].embeddedNodeInParent );
1728 return mLegend[nodeLayer].embeddedNodeInParent;
1737 return QIcon( qvariant_cast<QPixmap>( legendNode->
data( Qt::DecorationRole ) ) );
1743 if ( !
mLegend.contains( nodeLayer ) )
1744 return QList<QgsLayerTreeModelLegendNode *>();
1747 QList<QgsLayerTreeModelLegendNode *> lst(
data.activeNodes );
1748 if ( !skipNodeEmbeddedInParent &&
data.embeddedNodeInParent )
1749 lst.prepend(
data.embeddedNodeInParent );
1755 return mLegend.value( nodeLayer ).originalNodes;
1760 for (
auto it =
mLegend.constBegin(); it !=
mLegend.constEnd(); ++it )
1763 if ( layer->
layerId() == layerId )
1765 const auto activeNodes =
mLegend.value( layer ).activeNodes;
1804 QList<QgsSymbolLegendNode *> symbolNodes;
1805 QMap<QString, int> widthMax;
1813 widthMax[parentKey] = std::max( sz.width(), widthMax.contains( parentKey ) ? widthMax[parentKey] : 0 );
1815 symbolNodes.append( n );
1821 Q_ASSERT( widthMax[parentKey] > 0 );
1822 const int twiceMarginWidth = 2;
1823 n->setIconSize( QSize( widthMax[parentKey] + twiceMarginWidth, n->iconSize().rheight() + twiceMarginWidth ) );
1832void QgsLayerTreeModel::layerProfileGenerationPropertyChanged()
1838 if ( !elevationProperties )
1841 if (
QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( elevationProperties->parent() ) )
@ UsersCannotToggleEditing
Indicates that users are not allowed to toggle editing for this layer. Note that this does not imply ...
@ SkipVisibilityCheck
If set, the standard visibility check should be skipped.
@ RenderSymbolPreview
The render is for a symbol preview only and map based properties may not be available,...
@ RenderLayerTree
The render is for a layer tree display where map based properties are not available and where avoidan...
@ Antialiasing
Use antialiasing while drawing.
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.
static QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling.
A legend node which renders a color ramp.
virtual QString dataSourceUri(bool expandAuthConfig=false) const
Gets the data source specification.
Stores the component parts of a data source URI (e.g.
bool useEstimatedMetadata() const
Returns true if estimated metadata should be used for the connection.
A geometry is the spatial representation of a feature.
static QIcon iconForLayer(const QgsMapLayer *layer)
Returns the icon corresponding to a specified map layer.
static bool loadLayerDefinition(const QString &path, QgsProject *project, QgsLayerTreeGroup *rootGroup, QString &errorMessage, Qgis::LayerTreeInsertionMethod insertMethod=Qgis::LayerTreeInsertionMethod::OptimalInInsertionGroup, const QgsLayerTreeRegistryBridge::InsertionPoint *insertPoint=nullptr)
Loads the QLR at path into QGIS.
static bool exportLayerDefinition(const QString &path, const QList< QgsLayerTreeNode * > &selectedTreeNodes, QString &errorMessage)
Exports the selected layer tree nodes to a QLR file.
QString name() const override
Returns the node's name.
void setName(const QString &name) override
Sets the node's name.
Contains settings relating to filtering the contents of QgsLayerTreeModel and views.
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.
An abstract interface for legend items returned from QgsMapLayerLegend implementation.
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.
@ SymbolLegend
Vector symbol legend node type.
@ ParentRuleKey
Rule key of the parent legend node - for legends with tree hierarchy (QString). Added in 2....
@ NodeType
Type of node. Added in 3.16.
@ RuleKey
Rule key of the node (QString).
@ IsDataDefinedSize
Set when a node is related to data defined size (title or separated legend items)....
virtual void invalidateMapBasedData()
Notification from model that information from associated map view has changed.
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.
QgsLayerTreeLayer * layerNode() const
Returns pointer to the parent layer node.
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()
void setFilterSettings(const QgsLayerTreeFilterSettings *settings=nullptr)
Sets the filter settings to use to filter legend nodes.
QVariant legendNodeData(QgsLayerTreeModelLegendNode *node, int role) const
void hitTestStarted()
Emitted when a hit test for visible legend items starts.
double mLegendMapViewScale
void setRootGroup(QgsLayerTree *newRootGroup)
Reset the model and use a new root group node.
Q_DECL_DEPRECATED 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
void hitTestCompleted()
Emitted when a hit test for visible legend items completes.
std::unique_ptr< QgsLayerTreeFilterSettings > mFilterSettings
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
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)
QMap< QString, QSet< QString > > mHitTestResults
QModelIndex parent(const QModelIndex &child) const override
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.
bool hitTestInProgress() const
Returns true if a hit test for visible legend items is currently in progress.
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()
Triggered 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
QgsRenderContext * createTemporaryRenderContext() const
Returns a temporary render context.
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.
QSet< QgsScreenProperties > targetScreenProperties() const
Returns the target screen properties to use when generating icons.
QStringList mimeTypes() const override
QMimeData * mimeData(const QModelIndexList &indexes) const override
QSet< QgsScreenProperties > mTargetScreenProperties
void nodeRemovedChildren()
int rowCount(const QModelIndex &parent=QModelIndex()) const override
QPointer< QgsMapHitTestTask > mHitTestTask
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
QMap< QString, QPair< double, double > > mHitTestResultsRendererUpdatedCanvas
QList< QgsLayerTreeModelLegendNode * > filterLegendNodes(const QList< QgsLayerTreeModelLegendNode * > &nodes)
Filter nodes from QgsMapLayerLegend according to the current filtering rules.
const QgsLayerTreeFilterSettings * filterSettings() const
Returns the filter settings to use to filter legend nodes.
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)
const QgsMapSettings * legendFilterMapSettings() const
Returns the current map settings used for the current legend filter (or nullptr if none is enabled).
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 waitForHitTestBlocking()
When a current hit test for visible legend items is in progress, calling this method will block until...
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)....
@ UseThreadedHitTest
Run legend hit tests in a background thread.
void addTargetScreenProperties(const QgsScreenProperties &properties)
Adds additional target screen properties to use when generating icons for Qt::DecorationRole data.
Flags mFlags
Sets of flags for the model.
Q_DECL_DEPRECATED 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.
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).
void setCustomProperty(const QString &key, const QVariant &value)
Sets a custom property for the node. Properties are stored in a map and saved in project file.
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.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
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.
QgsLayerTreeNode * parent()
Gets pointer to the parent. If parent is nullptr, the node is a root node.
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.
void addedChildren(QgsLayerTreeNode *node, int indexFrom, int indexTo)
Emitted when one or more nodes have been added to a node within the tree.
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.
Namespace with helper functions for layer tree operations.
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
static bool isGroup(QgsLayerTreeNode *node)
Check whether the node is a valid group node.
static QgsLayerTreeGroup * toGroup(QgsLayerTreeNode *node)
Cast node to a group.
static bool isCustomNode(const QgsLayerTreeNode *node)
Check whether the node is a valid custom node.
static QgsLayerTreeCustomNode * toCustomNode(QgsLayerTreeNode *node)
Cast node to a custom node.
Executes a QgsMapHitTest in a background thread.
Base class for storage of map layer elevation properties.
void profileGenerationPropertyChanged()
Emitted when any of the elevation properties which relate solely to generation of elevation profiles ...
static void applyLayerNodeProperties(QgsLayerTreeLayer *nodeLayer, QList< QgsLayerTreeModelLegendNode * > &nodes)
update according to layer node's custom properties (order of items, user labels for items)
An 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.
void editingStopped()
Emitted when edited changes have been successfully written to the data provider.
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
void editingStarted()
Emitted when editing on this layer has started.
virtual Qgis::MapLayerProperties properties() const
Returns the map layer properties of this layer.
virtual bool isEditable() const
Returns true if the layer can be edited.
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
virtual bool isModified() const
Returns true if the layer has been modified since last commit/save.
void flagsChanged()
Emitted when layer's flags have been modified.
virtual QgsMapLayerElevationProperties * elevationProperties()
Returns the layer's elevation properties.
void layerModified()
Emitted when modifications has been done on layer.
Contains configuration for rendering maps.
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.
A container for the context for various read/write operations on objects.
Contains information about the context of a rendering operation.
Stores properties relating to a screen.
static const QgsSettingsEntryBool * settingsLayerTreeShowFeatureCountForNewLayers
Settings entry show feature counts for newly added layers by default.
static const QgsSettingsEntryBool * settingsLayerTreeShowIdInLayerTooltips
Settings entry for hidden ID in layer tooltips.
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.
long addTask(QgsTask *task, int priority=0)
Adds a task to the manager.
void taskCompleted()
Will be emitted by task to indicate its successful completion.
Represents a vector layer which manages a vector based dataset.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
QgsVectorDataProvider * dataProvider() final
Returns the layer's data provider, it may be nullptr.
static Q_INVOKABLE QString displayString(Qgis::WkbType type)
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
#define Q_NOWARN_DEPRECATED_POP
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
#define Q_NOWARN_DEPRECATED_PUSH
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.