50#include <QDomDocument>
55#include "moc_qgslayoutitemlegend.cpp"
57using namespace Qt::StringLiterals;
71 mIsDefaultLegend = isDefault;
81 if ( filter == mFilterToCheckedLayers )
84 mFilterToCheckedLayers = filter;
88bool QgsLegendFilterProxyModel::layerShown(
QgsMapLayer *layer )
const
115 connect( &
layout->atlasComposition(), &QgsAtlasComposition::renderEnded,
this, &QgsLayoutItemLegend::onAtlasEnded );
118 mTitle = mSettings.title();
124 emit backgroundTaskCountChanged( 0 );
172 const QPointF oldPos = pos();
174 ensureModelIsInitialized();
176 if ( mFilterAskedForUpdate )
178 mFilterAskedForUpdate =
false;
179 doUpdateFilterByMap();
182 const int dpi = painter->device()->logicalDpiX();
183 const double dotsPerMM = dpi / 25.4;
190 mSettings.setDpi( dpi );
202 const QSizeF mapSizePixels = QSizeF( mMap->rect().width() * dotsPerMM, mMap->rect().height() * dotsPerMM );
205 const QgsMapSettings ms = mMap->mapSettings( mapExtent, mapSizePixels, dpi,
false );
209 mSettings.setMapScale( ms.
scale() );
212 mInitialMapScaleCalculated =
true;
215 legendRenderer.
setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() );
218 if ( mSizeToContents )
224 const QSizeF size = legendRenderer.
minimumSize( &context );
227 mForceResize =
false;
233 else if ( size.height() > rect().height() || size.width() > rect().width() )
236 QSizeF targetSize = rect().size();
237 if ( size.height() > targetSize.height() )
238 targetSize.setHeight( size.height() );
239 if ( size.width() > targetSize.width() )
240 targetSize.setWidth( size.width() );
254 painter->translate( pos() - oldPos );
261 if ( !mMapUuid.isEmpty() )
263 setLinkedMap( qobject_cast< QgsLayoutItemMap * >(
mLayout->itemByUuid( mMapUuid,
true ) ) );
266 if ( !mFilterByMapUuids.isEmpty() )
268 QList< QgsLayoutItemMap * > maps;
269 maps.reserve( mFilterByMapUuids.size() );
270 for (
const QString &
uuid : std::as_const( mFilterByMapUuids ) )
284 clearLegendCachedData();
290 clearLegendCachedData();
309 painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
311 if ( !mSizeToContents )
314 const QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() );
315 painter->setClipRect( thisPaintRect );
322 mSettings.setDpi(
mLayout->renderContext().dpi() );
334 if ( !mSizeToContents )
337 if ( !mInitialMapScaleCalculated )
351 const QSizeF size = legendRenderer.
minimumSize( &context );
352 QgsDebugMsgLevel( u
"width = %1 height = %2"_s.arg( size.width() ).arg( size.height() ), 2 );
353 if ( size.isValid() )
363 mSizeToContents = enabled;
368 return mSizeToContents;
371void QgsLayoutItemLegend::setCustomLayerTree(
QgsLayerTree *rootGroup )
373 if ( !mDeferLegendModelInitialization )
375 mLegendModel->setRootGroup( rootGroup ? rootGroup : (
mLayout ?
mLayout->project()->layerTreeRoot() :
nullptr ) );
378 mCustomLayerTree.reset( rootGroup );
381void QgsLayoutItemLegend::ensureModelIsInitialized()
const
383 if ( mDeferLegendModelInitialization )
386 mutableThis->mDeferLegendModelInitialization =
false;
387 mutableThis->setCustomLayerTree( mutableThis->mCustomLayerTree.release() );
393 QgsLegendRenderer res( mLegendModel.get(), mSettings );
395 QgsLegendFilterProxyModel *proxy =
new QgsLegendFilterProxyModel();
402 QgsExpressionContext expressionContext = mMap->createExpressionContext();
403 const QList<QgsMapLayer *> visibleLayers = mMap->layersToRender( &expressionContext );
410 if ( QgsProject *p = l->project() )
423 res.setProxyModel( proxy );
430 ensureModelIsInitialized();
431 return mLegendModel.get();
436 ensureModelIsInitialized();
437 return mLegendModel.get();
447 if ( mode == mSyncMode )
456 setCustomLayerTree(
nullptr );
475 std::unique_ptr< QgsLayerTree > customTree(
mLayout->project()->layerTreeRoot()->clone() );
477 QList<QgsMapLayer *> mapVisibleLayers;
483 mapVisibleLayers = mMap->layersToRender( &expressionContext );
490 mapVisibleLayers = p->layerTreeRoot()->checkedLayers();
497 filterNodeChildren = [mapVisibleLayers, mode, &filterNodeChildren](
QgsLayerTreeGroup * group )
502 const QList<QgsLayerTreeNode *> children = group->children();
507 group->removeChildNode( child );
521 group->removeChildNode( child );
525 group->removeChildNode( child );
531 filterNodeChildren( customTree.get() );
533 setCustomLayerTree( customTree.release() );
536void QgsLayoutItemLegend::nodeCustomPropertyChanged(
QgsLayerTreeNode *,
const QString &key )
538 if ( key ==
"cached_name"_L1 )
583 if ( mLegendFilterByMap == enabled )
586 mLegendFilterByMap = enabled;
593 mSettings.setTitle( t );
595 if (
mLayout &&
id().isEmpty() )
598 mLayout->itemsModel()->updateItemDisplayName(
this );
608 return mSettings.titleAlignment();
613 mSettings.setTitleAlignment( alignment );
618 return mSettings.rstyle( s );
623 return mSettings.style( s );
628 mSettings.setStyle( s,
style );
634 return mSettings.style( s ).font();
658 return mSettings.lineSpacing();
665 mSettings.setLineSpacing( spacing );
671 return mSettings.boxSpace();
676 mSettings.setBoxSpace( s );
681 return mSettings.columnSpace();
686 mSettings.setColumnSpace( s );
692 return mSettings.fontColor();
699 mSettings.setFontColor(
c );
705 return mSettings.symbolSize().width();
710 mSettings.setSymbolSize( QSizeF( w, mSettings.symbolSize().height() ) );
715 return mSettings.maximumSymbolSize();
720 mSettings.setMaximumSymbolSize( size );
725 return mSettings.minimumSymbolSize();
730 mSettings.setMinimumSymbolSize( size );
735 mSettings.setSymbolAlignment( alignment );
740 return mSettings.symbolAlignment();
745 return mSettings.symbolSize().height();
750 mSettings.setSymbolSize( QSizeF( mSettings.symbolSize().width(), h ) );
755 return mSettings.wmsLegendSize().width();
760 mSettings.setWmsLegendSize( QSizeF( w, mSettings.wmsLegendSize().height() ) );
765 return mSettings.wmsLegendSize().height();
769 mSettings.setWmsLegendSize( QSizeF( mSettings.wmsLegendSize().width(), h ) );
774 mSettings.setWrapChar( t );
779 return mSettings.wrapChar();
790 mSettings.setColumnCount(
c );
795 return mSettings.splitLayer();
800 mSettings.setSplitLayer( s );
805 return mSettings.equalColumnWidth();
810 mSettings.setEqualColumnWidth( s );
815 return mSettings.drawRasterStroke();
820 mSettings.setDrawRasterStroke( enabled );
825 return mSettings.rasterStrokeColor();
830 mSettings.setRasterStrokeColor( color );
835 return mSettings.rasterStrokeWidth();
840 mSettings.setRasterStrokeWidth( width );
845 return mSettings.autoWrapLinesAfter();
850 mSettings.setAutoWrapLinesAfter( length );
863 legendElem.setAttribute( u
"title"_s, mTitle );
864 legendElem.setAttribute( u
"titleAlignment"_s, QString::number(
static_cast< int >( mSettings.titleAlignment() ) ) );
865 legendElem.setAttribute( u
"columnCount"_s, QString::number( mColumnCount ) );
866 legendElem.setAttribute( u
"splitLayer"_s, QString::number( mSettings.splitLayer() ) );
867 legendElem.setAttribute( u
"equalColumnWidth"_s, QString::number( mSettings.equalColumnWidth() ) );
869 legendElem.setAttribute( u
"boxSpace"_s, QString::number( mSettings.boxSpace() ) );
870 legendElem.setAttribute( u
"columnSpace"_s, QString::number( mSettings.columnSpace() ) );
872 legendElem.setAttribute( u
"symbolWidth"_s, QString::number( mSettings.symbolSize().width() ) );
873 legendElem.setAttribute( u
"symbolHeight"_s, QString::number( mSettings.symbolSize().height() ) );
874 legendElem.setAttribute( u
"maxSymbolSize"_s, QString::number( mSettings.maximumSymbolSize() ) );
875 legendElem.setAttribute( u
"minSymbolSize"_s, QString::number( mSettings.minimumSymbolSize() ) );
877 legendElem.setAttribute( u
"symbolAlignment"_s, mSettings.symbolAlignment() );
879 legendElem.setAttribute( u
"symbolAlignment"_s, mSettings.symbolAlignment() );
881 legendElem.setAttribute( u
"rasterBorder"_s, mSettings.drawRasterStroke() );
883 legendElem.setAttribute( u
"rasterBorderWidth"_s, QString::number( mSettings.rasterStrokeWidth() ) );
885 if ( mSettings.autoWrapLinesAfter() > 0 )
887 legendElem.setAttribute( u
"autoWrapLinesAfter"_s, mSettings.autoWrapLinesAfter() );
890 legendElem.setAttribute( u
"wmsLegendWidth"_s, QString::number( mSettings.wmsLegendSize().width() ) );
891 legendElem.setAttribute( u
"wmsLegendHeight"_s, QString::number( mSettings.wmsLegendSize().height() ) );
892 legendElem.setAttribute( u
"wrapChar"_s, mSettings.wrapChar() );
894 legendElem.setAttribute( u
"resizeToContents"_s, mSizeToContents );
898 legendElem.setAttribute( u
"map_uuid"_s, mMap->uuid() );
901 if ( !mFilterByMapItems.empty() )
903 QDomElement filterByMapsElem = doc.createElement( u
"filterByMaps"_s );
908 QDomElement mapElem = doc.createElement( u
"map"_s );
909 mapElem.setAttribute( u
"uuid"_s, map->uuid() );
910 filterByMapsElem.appendChild( mapElem );
913 legendElem.appendChild( filterByMapsElem );
916 QDomElement legendStyles = doc.createElement( u
"styles"_s );
917 legendElem.appendChild( legendStyles );
925 if ( mCustomLayerTree )
928 mCustomLayerTree->writeXml( legendElem, context );
935 if ( mLegendFilterByMap )
937 legendElem.setAttribute( u
"legendFilterByMap"_s, u
"1"_s );
939 legendElem.setAttribute( u
"legendFilterByAtlas"_s, mFilterOutAtlas ? u
"1"_s : u
"0"_s );
947 mTitle = itemElem.attribute( u
"title"_s );
948 mSettings.setTitle( mTitle );
949 if ( !itemElem.attribute( u
"titleAlignment"_s ).isEmpty() )
951 mSettings.setTitleAlignment(
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( u
"titleAlignment"_s ).toInt() ) );
953 int colCount = itemElem.attribute( u
"columnCount"_s, u
"1"_s ).toInt();
954 if ( colCount < 1 ) colCount = 1;
955 mColumnCount = colCount;
956 mSettings.setColumnCount( mColumnCount );
957 mSettings.setSplitLayer( itemElem.attribute( u
"splitLayer"_s, u
"0"_s ).toInt() == 1 );
958 mSettings.setEqualColumnWidth( itemElem.attribute( u
"equalColumnWidth"_s, u
"0"_s ).toInt() == 1 );
960 const QDomNodeList stylesNodeList = itemElem.elementsByTagName( u
"styles"_s );
961 if ( !stylesNodeList.isEmpty() )
963 const QDomNode stylesNode = stylesNodeList.at( 0 );
964 for (
int i = 0; i < stylesNode.childNodes().size(); i++ )
966 const QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
968 style.readXml( styleElem, doc, context );
969 const QString name = styleElem.attribute( u
"name"_s );
982 if ( itemElem.hasAttribute( u
"fontColor"_s ) )
985 fontClr.setNamedColor( itemElem.attribute( u
"fontColor"_s, u
"#000000"_s ) );
993 mSettings.setBoxSpace( itemElem.attribute( u
"boxSpace"_s, u
"2.0"_s ).toDouble() );
994 mSettings.setColumnSpace( itemElem.attribute( u
"columnSpace"_s, u
"2.0"_s ).toDouble() );
996 mSettings.setSymbolSize( QSizeF( itemElem.attribute( u
"symbolWidth"_s, u
"7.0"_s ).toDouble(), itemElem.attribute( u
"symbolHeight"_s, u
"14.0"_s ).toDouble() ) );
997 mSettings.setSymbolAlignment(
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( u
"symbolAlignment"_s, QString::number( Qt::AlignLeft ) ).toInt() ) );
999 mSettings.setMaximumSymbolSize( itemElem.attribute( u
"maxSymbolSize"_s, u
"0.0"_s ).toDouble() );
1000 mSettings.setMinimumSymbolSize( itemElem.attribute( u
"minSymbolSize"_s, u
"0.0"_s ).toDouble() );
1002 mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( u
"wmsLegendWidth"_s, u
"50"_s ).toDouble(), itemElem.attribute( u
"wmsLegendHeight"_s, u
"25"_s ).toDouble() ) );
1004 if ( itemElem.hasAttribute( u
"lineSpacing"_s ) )
1006 const double spacing = itemElem.attribute( u
"lineSpacing"_s, u
"1.0"_s ).toDouble();
1030 mSettings.setDrawRasterStroke( itemElem.attribute( u
"rasterBorder"_s, u
"1"_s ) !=
"0"_L1 );
1032 mSettings.setRasterStrokeWidth( itemElem.attribute( u
"rasterBorderWidth"_s, u
"0"_s ).toDouble() );
1034 mSettings.setAutoWrapLinesAfter( itemElem.attribute( u
"autoWrapLinesAfter"_s, u
"0"_s ).toDouble() );
1036 mSettings.setWrapChar( itemElem.attribute( u
"wrapChar"_s ) );
1038 mSizeToContents = itemElem.attribute( u
"resizeToContents"_s, u
"1"_s ) !=
"0"_L1;
1041 mLegendFilterByMap = itemElem.attribute( u
"legendFilterByMap"_s, u
"0"_s ).toInt();
1044 if ( !itemElem.attribute( u
"map_uuid"_s ).isEmpty() )
1046 mMapUuid = itemElem.attribute( u
"map_uuid"_s );
1049 mFilterByMapUuids.clear();
1051 const QDomElement filterByMapsElem = itemElem.firstChildElement( u
"filterByMaps"_s );
1052 if ( !filterByMapsElem.isNull() )
1054 QDomElement mapsElem = filterByMapsElem.firstChildElement( u
"map"_s );
1055 while ( !mapsElem.isNull() )
1057 mFilterByMapUuids << mapsElem.attribute( u
"uuid"_s );
1058 mapsElem = mapsElem.nextSiblingElement( u
"map"_s );
1061 else if ( !mMapUuid.isEmpty() )
1064 mFilterByMapUuids << mMapUuid;
1069 setupMapConnections( mMap,
false );
1072 mFilterOutAtlas = itemElem.attribute( u
"legendFilterByAtlas"_s, u
"0"_s ).toInt();
1075 QDomElement layerTreeElem = itemElem.firstChildElement( u
"layer-tree"_s );
1076 if ( layerTreeElem.isNull() )
1077 layerTreeElem = itemElem.firstChildElement( u
"layer-tree-group"_s );
1079 if ( !layerTreeElem.isNull() )
1083 tree->resolveReferences(
mLayout->project(),
true );
1084 setCustomLayerTree( tree.release() );
1089 setCustomLayerTree(
nullptr );
1098 if ( !
id().isEmpty() )
1104 QString text = mSettings.title();
1105 if ( text.isEmpty() )
1107 return tr(
"<Legend>" );
1109 if ( text.length() > 25 )
1111 return tr(
"%1…" ).arg( text.left( 25 ) );
1121 return blendMode() != QPainter::CompositionMode_SourceOver;
1126 return mEvaluatedOpacity < 1.0;
1129void QgsLayoutItemLegend::setupMapConnections(
QgsLayoutItemMap *map,
bool connectSlots )
1134 if ( !connectSlots )
1136 disconnect( map, &QObject::destroyed,
this, &QgsLayoutItemLegend::invalidateCurrentMap );
1145 connect( map, &QObject::destroyed,
this, &QgsLayoutItemLegend::invalidateCurrentMap );
1161 setupMapConnections( mMap,
false );
1168 setupMapConnections( mMap,
true );
1169 mapThemeChanged( mMap->themeToRender( mMap->createExpressionContext() ) );
1182 setupMapConnections( map,
false );
1185 mFilterByMapItems.clear();
1186 mFilterByMapItems.reserve( maps.size() );
1191 mFilterByMapItems.append( map );
1192 setupMapConnections( map,
true );
1201 QList<QgsLayoutItemMap *> res;
1202 res.reserve( mFilterByMapItems.size() );
1211void QgsLayoutItemLegend::invalidateCurrentMap()
1220 bool forceUpdate =
false;
1228 mSettings.setTitle( t );
1236 if ( ok && cols >= 0 )
1238 mSettings.setColumnCount( cols );
1246 if ( ok && width >= 0 )
1248 mSettings.setAutoWrapLinesAfter( width );
1262void QgsLayoutItemLegend::updateFilterByMapAndRedraw()
1267void QgsLayoutItemLegend::setModelStyleOverrides(
const QMap<QString, QString> &overrides )
1269 mLegendModel->setLayerStyleOverrides( overrides );
1270 if ( QgsLayerTree *rootGroup = mLegendModel->rootGroup() )
1272 const QList< QgsLayerTreeLayer * > layers = rootGroup->
findLayers();
1273 for ( QgsLayerTreeLayer *nodeLayer : std::as_const( layers ) )
1274 mLegendModel->refreshLayerLegend( nodeLayer );
1278void QgsLayoutItemLegend::clearLegendCachedData()
1280 std::function< void( QgsLayerTreeNode * ) > clearNodeCache;
1281 clearNodeCache = [&]( QgsLayerTreeNode * node )
1283 mLegendModel->clearCachedData( node );
1287 const QList< QgsLayerTreeNode * > children = group->
children();
1288 for ( QgsLayerTreeNode *child : children )
1290 clearNodeCache( child );
1295 if ( QgsLayerTree *rootGroup = mLegendModel->rootGroup() )
1297 clearNodeCache( rootGroup );
1301void QgsLayoutItemLegend::mapLayerStyleOverridesChanged()
1307 if ( mLegendFilterByMap )
1315 setModelStyleOverrides( mMap->layerStyleOverrides() );
1323void QgsLayoutItemLegend::mapThemeChanged(
const QString &theme )
1325 if ( mThemeName == theme )
1346 mFilterAskedForUpdate =
true;
1352void QgsLayoutItemLegend::doUpdateFilterByMap()
1362 if ( mMap && !mThemeName.isEmpty() )
1365 const QMap<QString, QString> overrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
1366 setModelStyleOverrides( overrides );
1370 mLegendModel->setLayerStyleOverrides( mMap->layerStyleOverrides() );
1374 mLegendModel->setLayerStyleOverrides( QMap<QString, QString>() );
1383 const bool hasValidFilter = filterByExpression
1384 || ( mLegendFilterByMap && ( mMap || !mFilterByMapItems.empty() ) )
1386 || requiresFilteringBecauseOfRendererSetting();
1388 if ( hasValidFilter )
1390 const double dpi =
mLayout->renderContext().dpi();
1392 QSet< QgsLayoutItemMap * > linkedFilterMaps;
1393 if ( mLegendFilterByMap )
1397 linkedFilterMaps.insert( mMap );
1400 QgsMapSettings mapSettings;
1401 QgsGeometry filterGeometry;
1405 const QgsRectangle requestRectangle = mMap->requestedExtent();
1406 QSizeF size( requestRectangle.
width(), requestRectangle.
height() );
1408 mapSettings = mMap->mapSettings( requestRectangle, size, dpi,
true );
1412 else if ( !linkedFilterMaps.empty() )
1415 const QgsRectangle requestRectangle = ( *linkedFilterMaps.constBegin() )->requestedExtent();
1416 QSizeF size( requestRectangle.
width(), requestRectangle.
height() );
1418 mapSettings = ( *linkedFilterMaps.constBegin() )->mapSettings( requestRectangle, size, dpi,
true );
1425 const QgsGeometry atlasGeometry {
mLayout->reportContext().currentGeometry( mapSettings.
destinationCrs() ) };
1427 QgsLayerTreeFilterSettings filterSettings( mapSettings );
1429 QList<QgsMapLayer *> layersToClip;
1432 if ( !atlasGeometry.
isNull() && mMap->atlasClippingSettings()->enabled() )
1434 layersToClip = mMap->atlasClippingSettings()->layersToClip();
1435 for ( QgsMapLayer *layer : std::as_const( layersToClip ) )
1437 QList<QgsMapLayer *> mapLayers { filterSettings.mapSettings().layers(
true ) };
1438 mapLayers.removeAll( layer );
1439 filterSettings.mapSettings().setLayers( mapLayers );
1440 filterSettings.addVisibleExtentForLayer( layer, QgsReferencedGeometry( atlasGeometry, mapSettings.
destinationCrs() ) );
1445 if ( !linkedFilterMaps.empty() )
1461 catch ( QgsCsException & )
1466 const QList< QgsMapLayer * > layersForMap = map->
layersToRender();
1467 for ( QgsMapLayer *layer : layersForMap )
1469 if ( mInAtlas && !atlasGeometry.
isNull() )
1474 filterSettings.addVisibleExtentForLayer( layer, QgsReferencedGeometry( mapExtent, mapSettings.
destinationCrs() ) );
1481 if ( !filterGeometry.
isEmpty() )
1487 filterSettings.setLayerFilterExpressionsFromLayerTree( mLegendModel->rootGroup() );
1488 if ( !filterGeometry.
isNull() )
1490 filterSettings.setFilterPolygon( filterGeometry );
1497 mLegendModel->setFilterSettings( &filterSettings );
1501 mLegendModel->setFilterSettings(
nullptr );
1504 clearLegendCachedData();
1505 mForceResize =
true;
1515 mFilterOutAtlas = doFilter;
1520 return mFilterOutAtlas;
1523void QgsLayoutItemLegend::onAtlasFeature()
1527 mInAtlas = mFilterOutAtlas;
1531void QgsLayoutItemLegend::onAtlasEnded()
1545 context.
appendScope( mMap->createExpressionContext().popScope() );
1571 const QList<QgsLayerTreeNode *> childNodes = group->
children();
1577 if ( !visit( nodeGroup ) )
1589 const QList<QgsLayerTreeModelLegendNode *> legendNodes = mLegendModel->layerLegendNodes( nodeLayer );
1594 if ( !symbolNode->patchShape().isNull() )
1606 return visit(
model()->rootGroup( ) );
1611 return mLegendModel->hitTestInProgress();
1615bool QgsLayoutItemLegend::requiresFilteringBecauseOfRendererSetting()
1623 if ( !mapLayer || !mapLayer->
isValid() )
1625 if (
QgsRasterLayer *rl = qobject_cast<QgsRasterLayer *>( mapLayer ) )
1632 else if ( QgsMeshLayer *ml = qobject_cast<QgsMeshLayer *>( mapLayer ) )
1634 const QgsMeshDatasetIndex activeDatasetIndex = ml->staticScalarDatasetIndex();
1636 if ( activeDatasetIndex.
isValid() )
1638 QgsMeshRendererScalarSettings scalarRendererSettings = ml->rendererSettings().scalarSettings( activeDatasetIndex.
group() );
1655 , mLayoutLegend( layout )
1665 , mLayoutLegend( layout )
1679 if ( nodeLayer && ( role == Qt::DisplayRole || role == Qt::EditRole ) )
1681 QString name = node->
customProperty( u
"cached_name"_s ).toString();
1682 if ( !name.isEmpty() )
1688 name = nodeLayer->
customProperty( u
"legend/title-label"_s ).toString();
1689 if ( name.isEmpty() )
1690 name = nodeLayer->
name();
1691 if ( name.isEmpty() )
1692 name = node->
customProperty( u
"legend/title-label"_s ).toString();
1693 if ( name.isEmpty() )
1694 name = node->
name();
1695 if ( nodeLayer->
customProperty( u
"showFeatureCount"_s, 0 ).toInt() )
1721 if ( !
mLegend.contains( nodeLayer ) )
1722 return QList<QgsLayerTreeModelLegendNode *>();
1725 QList<QgsLayerTreeModelLegendNode *> lst(
data.activeNodes );
1726 if ( !skipNodeEmbeddedInParent &&
data.embeddedNodeInParent )
1727 lst.prepend(
data.embeddedNodeInParent );
1736void QgsLegendModel::forceRefresh()
@ Millimeters
Millimeters.
LegendComponent
Component of legends which can be styled.
@ Symbol
Symbol icon (excluding label).
@ Group
Legend group title.
@ Subgroup
Legend subgroup title.
@ SymbolLabel
Symbol label (excluding icon).
LegendSyncMode
Legend synchronization mode.
@ VisibleLayers
Synchronize to map layers. The legend will include layers which are included in the linked map only.
@ AllProjectLayers
Synchronize to all project layers.
@ Manual
No automatic synchronization of legend layers. The legend will be manually populated.
@ SkipVisibilityCheck
If set, the standard visibility check should be skipped.
@ UpdatedCanvas
Constantly updated extent of the canvas is used to compute statistics.
@ ExcludeByDefault
If set, the layer should not be included in legends by default, and must be manually added by a user.
@ UpdatedCanvas
Constantly updated extent of the canvas is used to compute statistics.
@ Millimeters
Millimeters.
@ ApplyScalingWorkaroundForTextRendering
Whether a scaling workaround designed to stablise the rendering of small font sizes (or for painters ...
@ SynchronousLegendGraphics
Query legend graphics synchronously.
@ UseAdvancedEffects
Enable advanced effects such as blend modes.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QColor colorFromString(const QString &string)
Decodes a string into a color value.
static QString colorToString(const QColor &color)
Encodes a color into a string value.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters ¶meters=QgsGeometryParameters()) const
Returns a geometry representing the points shared by this geometry and other.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
virtual bool isLayerChecked(QgsMapLayer *layer) const
Returns if the layer is checked or not.
void setCheckedLayers(const QList< QgsMapLayer * > layers)
Initialize the list of checked layers.
void setShowPrivateLayers(bool showPrivate)
Determines if private layers are shown.
QModelIndex parent(const QModelIndex &child) const override
QgsLayerTreeFilterProxyModel(QObject *parent=nullptr)
Constructor.
Layer tree group node serves as a container for layers and further groups.
QList< QgsLayerTreeLayer * > findLayers() const
Find all layer nodes.
Layer tree node points to a map layer.
QgsLegendPatchShape patchShape() const
Returns the symbol patch shape to use when rendering the legend node symbol.
QString name() const override
Returns the layer's name.
QgsMapLayer * layer() const
Returns the map layer associated with this node.
An abstract interface for legend items returned from QgsMapLayerLegend implementation.
Flags flags() const
Returns OR-ed combination of model flags.
void hitTestStarted()
Emitted when a hit test for visible legend items starts.
void hitTestCompleted()
Emitted when a hit test for visible legend items completes.
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
QgsLayerTreeModel(QgsLayerTree *rootNode, QObject *parent=nullptr)
Construct a new tree model with given layer tree (root node must not be nullptr).
QModelIndex parent(const QModelIndex &child) const override
void setFlag(Flag f, bool on=true)
Enable or disable a model flag.
QHash< QgsLayerTreeLayer *, LayerLegendData > mLegend
Per layer data about layer's legend nodes.
QgsLayerTree * rootGroup() const
Returns pointer to the root node of the layer tree. Always a non nullptr value.
QgsLayerTreeNode * index2node(const QModelIndex &index) const
Returns layer tree node for given index.
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
static QgsLayerTreeModelLegendNode * index2legendNode(const QModelIndex &index)
Returns legend node for given index.
@ AllowNodeReorder
Allow reordering with drag'n'drop.
@ AllowLegendChangeState
Allow check boxes for legend nodes (if supported by layer's legend).
@ UseThreadedHitTest
Run legend hit tests in a background thread.
Base class for nodes in a layer tree.
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.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
void removeCustomProperty(const QString &key)
Remove a custom property from layer. Properties are stored in a map and saved in project file.
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.
virtual QString name() const =0
Returns name of the node.
void customPropertyChanged(QgsLayerTreeNode *node, const QString &key)
Emitted when a custom property of a node within the tree has been changed or removed.
void visibilityChanged(QgsLayerTreeNode *node)
Emitted when check state of a node within the tree has been changed.
static bool hasLegendFilterExpression(const QgsLayerTreeGroup &group)
Test if one of the layers in a group has an expression filter.
Namespace with helper functions for layer tree operations.
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
static std::unique_ptr< QgsLayerTree > readXml(const QDomElement &element, const QgsReadWriteContext &context)
Load the layer tree from an XML element.
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.
A layout item subclass for map legends.
Q_DECL_DEPRECATED bool autoUpdateModel() const
Returns whether the legend content should auto update to reflect changes in the project's layer tree.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified style entity visitor, causing it to visit all style entities associated with th...
QString title() const
Returns the legend title.
void setSplitLayer(bool enabled)
Sets whether the legend items from a single layer can be split over multiple columns.
QgsLegendModel * model()
Returns the legend model.
QgsLegendStyle & rstyle(Qgis::LegendComponent s)
Returns reference to modifiable legend style.
void adjustBoxSize()
Sets the legend's item bounds to fit the whole legend content.
double wmsLegendWidth() const
Returns the WMS legend width.
void setColumnSpace(double spacing)
Sets the legend column spacing.
void setBoxSpace(double space)
Sets the legend box space.
Qgis::LegendSyncMode syncMode() const
Returns the legend's synchronization mode.
bool splitLayer() const
Returns whether the legend items from a single layer can be split over multiple columns.
double symbolHeight() const
Returns the legend symbol height.
void updateFilterByMap(bool redraw=true)
Updates the legend content when filtered by map.
void setEqualColumnWidth(bool equalize)
Sets whether column widths should be equalized.
void setDrawRasterStroke(bool enabled)
Sets whether a stroke will be drawn around raster symbol items.
void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::DataDefinedProperty::AllProperties) override
static QgsLayoutItemLegend * create(QgsLayout *layout)
Returns a new legend item for the specified layout.
bool requiresRasterization() const override
Returns true if the item is drawn in such a way that forces the whole layout to be rasterized when ex...
static const QgsSettingsEntryEnumFlag< Qgis::LegendSyncMode > * settingDefaultLegendSyncMode
Settings entry - Layout legend synchronization mode.
void setLegendFilterOutAtlas(bool doFilter)
When set to true, during an atlas rendering, it will filter out legend elements where features are ou...
void setSymbolWidth(double width)
Sets the legend symbol width.
QString wrapString() const
Returns the legend text wrapping string.
bool resizeToContents() const
Returns whether the legend should automatically resize to fit its contents.
void setResizeToContents(bool enabled)
Sets whether the legend should automatically resize to fit its contents.
void updateLegend()
Updates the model and all legend entries.
QgsLayoutItemLegend(QgsLayout *layout)
Constructor for QgsLayoutItemLegend, with the specified parent layout.
void setLinkedMap(QgsLayoutItemMap *map)
Sets the map to associate with the legend.
bool writePropertiesToElement(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const override
Stores item state within an XML DOM element.
void setSymbolAlignment(Qt::AlignmentFlag alignment)
Sets the alignment for placement of legend symbols.
double autoWrapLinesAfter() const
Returns the maximum line length (in millimeters) allowed before lines of text in the legend will be a...
Q_DECL_DEPRECATED QColor fontColor() const
Returns the legend font color.
Qt::AlignmentFlag symbolAlignment() const
Returns the alignment for placement of legend symbols.
double maximumSymbolSize() const
Returns the maximum symbol size (in mm).
void setWmsLegendWidth(double width)
Sets the WMS legend width.
void setTitle(const QString &title)
Sets the legend title.
Q_DECL_DEPRECATED void setFontColor(const QColor &color)
Sets the legend font color.
double boxSpace() const
Returns the legend box space.
void setRasterStrokeColor(const QColor &color)
Sets the stroke color for the stroke drawn around raster symbol items.
QString displayName() const override
Gets item display name.
bool isRefreshing() const override
Returns true if the item is currently refreshing content in the background.
void paint(QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget) override
double symbolWidth() const
Returns the legend symbol width.
QColor rasterStrokeColor() const
Returns the stroke color for the stroke drawn around raster symbol items.
bool drawRasterStroke() const
Returns whether a stroke will be drawn around raster symbol items.
void draw(QgsLayoutItemRenderContext &context) override
Draws the item's contents using the specified item render context.
void finalizeRestoreFromXml() override
Called after all pending items have been restored from XML.
int type() const override
bool readPropertiesFromElement(const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context) override
Sets item state from a DOM element.
bool legendFilterOutAtlas() const
Returns whether to filter out legend elements outside of the current atlas feature.
ExportLayerBehavior exportLayerBehavior() const override
Returns the behavior of this item during exporting to layered exports (e.g.
Q_DECL_DEPRECATED QFont styleFont(Qgis::LegendComponent component) const
Returns the font settings for a legend component.
Q_DECL_DEPRECATED void setLineSpacing(double spacing)
Sets the spacing in-between multiple lines.
double columnSpace() const
Returns the legend column spacing.
QgsLayoutItem::Flags itemFlags() const override
Returns the item's flags, which indicate how the item behaves.
Qt::AlignmentFlag titleAlignment() const
Returns the alignment of the legend title.
void setFilterByMapItems(const QList< QgsLayoutItemMap * > &maps)
Sets the maps to use when filtering legend content by map extents.
void setAutoWrapLinesAfter(double length)
Sets the maximum line length (in millimeters) allowed before lines of text in the legend will be auto...
void setLegendFilterByMapEnabled(bool enabled)
Set whether legend items should be filtered to show just the ones visible in the associated map.
QList< QgsLayoutItemMap * > filterByMapItems() const
Returns the maps to use when filtering legend content by map extents.
void setSymbolHeight(double height)
Sets the legend symbol height.
void setMinimumSymbolSize(double size)
Set the minimum symbol size for symbol (in millimeters).
void setStyleMargin(Qgis::LegendComponent component, double margin)
Set the margin for a legend component.
void setSyncMode(Qgis::LegendSyncMode mode)
Sets the legend's synchronization mode.
Q_DECL_DEPRECATED void setAutoUpdateModel(bool autoUpdate)
Sets whether the legend content should auto update to reflect changes in the project's layer tree.
void setMaximumSymbolSize(double size)
Set the maximum symbol size for symbol (in millimeters).
QIcon icon() const override
Returns the item's icon.
double wmsLegendHeight() const
Returns the WMS legend height.
void setWmsLegendHeight(double height)
Sets the WMS legend height.
QgsLegendStyle style(Qgis::LegendComponent s) const
Returns legend style.
void setRasterStrokeWidth(double width)
Sets the stroke width for the stroke drawn around raster symbol items.
bool containsAdvancedEffects() const override
Returns true if the item contains contents with blend modes or transparency effects which can only be...
double minimumSymbolSize() const
Returns the minimum symbol size (in mm).
void setStyle(Qgis::LegendComponent component, const QgsLegendStyle &style)
Sets the style of component to style for the legend.
double rasterStrokeWidth() const
Returns the stroke width (in layout units) for the stroke drawn around raster symbol items.
Q_DECL_DEPRECATED double lineSpacing() const
Returns the spacing in-between lines in layout units.
void invalidateCache() override
Q_DECL_DEPRECATED void setStyleFont(Qgis::LegendComponent component, const QFont &font)
Sets the style font for a legend component.
void setTitleAlignment(Qt::AlignmentFlag alignment)
Sets the alignment of the legend title.
void resetManualLayers(Qgis::LegendSyncMode mode)
Resets the current legend manual configuration, including layer set and settings.
void setWrapString(const QString &string)
Sets the legend text wrapping string.
QString themeName() const
Returns the name of the theme currently linked to the legend.
void setColumnCount(int count)
Sets the legend column count.
bool equalColumnWidth() const
Returns whether column widths should be equalized.
int columnCount() const
Returns the legend column count.
bool legendFilterByMapEnabled() const
Find out whether legend items are filtered to show just the ones visible in the associated map.
Layout graphical items for displaying a map.
void extentChanged()
Emitted when the map's extent changes.
void layerStyleOverridesChanged()
Emitted when layer style overrides are changed... a means to let associated legend items know they sh...
void mapRotationChanged(double newRotation)
Emitted when the map's rotation changes.
QList< QgsMapLayer * > layersToRender(const QgsExpressionContext *context=nullptr, bool includeInvalidLayers=false) const
Returns a list of the layers which will be rendered within this map item, considering any locked laye...
QPolygonF visibleExtentPolygon() const
Returns a polygon representing the current visible map extent, considering map extents and rotation.
void themeChanged(const QString &theme)
Emitted when the map's associated theme is changed.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
@ LayoutLegend
Legend item.
Contains settings and helpers relating to a render of a QgsLayoutItem.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
virtual void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::DataDefinedProperty::AllProperties)
Refreshes a data defined property for the item by reevaluating the property's value and redrawing the...
QgsLayoutSize sizeWithUnits() const
Returns the item's current size, including units.
QgsLayoutItem(QgsLayout *layout, bool manageZValue=true)
Constructor for QgsLayoutItem, with the specified parent layout.
void paint(QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget) override
Handles preparing a paint surface for the layout item and painting the item's content.
virtual void redraw()
Triggers a redraw (update) of the item.
friend class QgsLayoutItemMap
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
virtual void attemptResize(const QgsLayoutSize &size, bool includesFrame=false)
Attempts to resize the item to a specified target size.
@ FlagOverridesPaint
Item overrides the default layout item painting method.
virtual void invalidateCache()
Forces a deferred update of any cached image the item uses.
virtual QString uuid() const
Returns the item identification string.
QString id() const
Returns the item's ID name.
ExportLayerBehavior
Behavior of item when exporting to layered outputs.
@ MustPlaceInOwnLayer
Item must be placed in its own individual layer.
friend class QgsLayoutItemLegend
void refresh() override
Refreshes the item, causing a recalculation of any property overrides and recalculation of its positi...
QPainter::CompositionMode blendMode() const
Returns the item's composition blending mode.
QgsPropertyCollection mDataDefinedProperties
const QgsLayout * layout() const
Returns the layout the object is attached to.
void changed()
Emitted when the object's properties change.
QPointer< QgsLayout > mLayout
DataDefinedProperty
Data defined properties for different item types.
@ LegendAutoWrapWidth
Legend text automatic wrapping width.
@ LegendTitle
Legend title.
@ LegendColumnCount
Legend column count.
@ AllProperties
All properties for item.
Provides a method of storing sizes, consisting of a width and height, for use in QGIS layouts.
static QgsRenderContext createRenderContextForLayout(QgsLayout *layout, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout and painter destination.
static QgsRenderContext createRenderContextForMap(QgsLayoutItemMap *map, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout map and painter destination.
void setIsDefaultLegend(bool isDefault)
Sets whether the legend is showing the default legend for a project (as opposed to a customized legen...
void setFilterToCheckedLayers(bool filter)
Sets whether only checked layers should be shown.
QgsLegendFilterProxyModel(QObject *parent=nullptr)
Constructor for QgsLegendFilterProxyModel, with the specified parent object.
Item model implementation based on layer tree model for layout legend.
void clearCachedData(QgsLayerTreeNode *node) const
Clears any previously cached data for the specified node.
void refreshLegend()
Emitted to refresh the legend.
QgsLegendModel(QgsLayerTree *rootNode, QObject *parent=nullptr, QgsLayoutItemLegend *layout=nullptr)
Construct the model based on the given layer tree.
QVariant data(const QModelIndex &index, int role) const override
QList< QgsLayerTreeModelLegendNode * > layerLegendNodes(QgsLayerTreeLayer *nodeLayer, bool skipNodeEmbeddedInParent=false) const
Returns filtered list of active legend nodes attached to a particular layer node (by default it retur...
bool isNull() const
Returns true if the patch shape is a null QgsLegendPatchShape, which indicates that the default legen...
Handles automatic layout and rendering of legends.
QSizeF minimumSize(QgsRenderContext *renderContext=nullptr)
Runs the layout algorithm and returns the minimum size required for the legend.
void setLegendSize(QSizeF s)
Sets the preferred resulting legend size.
Q_DECL_DEPRECATED void drawLegend(QPainter *painter)
Draws the legend with given painter.
Contains detailed styling information relating to how a layout legend should be rendered.
QgsTextFormat & textFormat()
Returns the text format used for rendering this legend component.
void setMargin(Side side, double margin)
Sets the margin (in mm) for the specified side of the component.
Q_DECL_DEPRECATED void setFont(const QFont &font)
Sets the font used for rendering this legend component.
void writeXml(const QString &name, QDomElement &elem, QDomDocument &doc, const QgsReadWriteContext &context=QgsReadWriteContext()) const
Writes the component's style definition to an XML element.
void setTextFormat(const QgsTextFormat &format)
Sets the text format used for rendering this legend component.
An abstract interface for implementations of legends for one map layer.
Qgis::MapLayerLegendFlags flags() const
Returns flags associated with the legend.
Base class for all map layer types.
QgsMapLayerLegend * legend() const
Can be nullptr.
Contains configuration for rendering maps.
double scale() const
Returns the calculated map scale.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
bool isValid() const
Returns whether index is valid, ie at least groups is set.
int group() const
Returns a group index.
Qgis::MeshRangeExtent extent() const
Returns the mesh extent for minimum maximum calculation.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
Represents a raster layer.
A container for the context for various read/write operations on objects.
A rectangle specified with double values.
Contains information about the context of a rendering operation.
double scaleFactor() const
Returns the scaling factor for the render to convert painter units to physical sizes.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setFlag(Qgis::RenderContextFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
Scoped object for saving and restoring a QPainter object's state.
static QgsSettingsTreeNode * sTreeLayout
An interface for classes which can visit style entity (e.g.
virtual bool visit(const QgsStyleEntityVisitorInterface::StyleLeaf &entity)
Called when the visitor will visit a style entity.
A legend patch shape entity for QgsStyle databases.
Implementation of legend node interface for displaying preview of vector symbols and their labels and...
Container for all settings relating to text rendering.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
void setLineHeightUnit(Qgis::RenderUnit unit)
Sets the unit for the line height for text.
double size() const
Returns the size for rendered text.
void setLineHeight(double height)
Sets the line height for text.
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.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
#define Q_NOWARN_DEPRECATED_POP
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
#define Q_NOWARN_DEPRECATED_PUSH
#define QgsDebugMsgLevel(str, level)
Single variable definition for use within a QgsExpressionContextScope.
Structure that stores all data associated with one map layer.
Contains information relating to the style entity currently being visited.