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
116 connect( &
layout->atlasComposition(), &QgsAtlasComposition::renderEnded,
this, &QgsLayoutItemLegend::onAtlasEnded );
119 mTitle = mSettings.title();
124 emit backgroundTaskCountChanged( 0 );
170 const QPointF oldPos = pos();
172 ensureModelIsInitialized();
174 if ( mFilterAskedForUpdate )
176 mFilterAskedForUpdate =
false;
177 doUpdateFilterByMap();
180 const int dpi = painter->device()->logicalDpiX();
181 const double dotsPerMM = dpi / 25.4;
188 mSettings.setDpi( dpi );
200 const QSizeF mapSizePixels = QSizeF( mMap->rect().width() * dotsPerMM, mMap->rect().height() * dotsPerMM );
203 const QgsMapSettings ms = mMap->mapSettings( mapExtent, mapSizePixels, dpi,
false );
207 mSettings.setMapScale( ms.
scale() );
210 mInitialMapScaleCalculated =
true;
213 legendRenderer.
setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() );
216 if ( mSizeToContents )
221 const QSizeF size = legendRenderer.
minimumSize( &context );
224 mForceResize =
false;
230 else if ( size.height() > rect().height() || size.width() > rect().width() )
233 QSizeF targetSize = rect().size();
234 if ( size.height() > targetSize.height() )
235 targetSize.setHeight( size.height() );
236 if ( size.width() > targetSize.width() )
237 targetSize.setWidth( size.width() );
251 painter->translate( pos() - oldPos );
258 if ( !mMapUuid.isEmpty() )
260 setLinkedMap( qobject_cast< QgsLayoutItemMap * >(
mLayout->itemByUuid( mMapUuid,
true ) ) );
263 if ( !mFilterByMapUuids.isEmpty() )
265 QList< QgsLayoutItemMap * > maps;
266 maps.reserve( mFilterByMapUuids.size() );
267 for (
const QString &
uuid : std::as_const( mFilterByMapUuids ) )
281 clearLegendCachedData();
287 clearLegendCachedData();
306 painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
308 if ( !mSizeToContents )
311 const QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() );
312 painter->setClipRect( thisPaintRect );
319 mSettings.setDpi(
mLayout->renderContext().dpi() );
331 if ( !mSizeToContents )
334 if ( !mInitialMapScaleCalculated )
347 const QSizeF size = legendRenderer.
minimumSize( &context );
348 QgsDebugMsgLevel( u
"width = %1 height = %2"_s.arg( size.width() ).arg( size.height() ), 2 );
349 if ( size.isValid() )
359 mSizeToContents = enabled;
364 return mSizeToContents;
367void QgsLayoutItemLegend::setCustomLayerTree(
QgsLayerTree *rootGroup )
369 if ( !mDeferLegendModelInitialization )
371 mLegendModel->setRootGroup( rootGroup ? rootGroup : (
mLayout ?
mLayout->project()->layerTreeRoot() :
nullptr ) );
374 mCustomLayerTree.reset( rootGroup );
377void QgsLayoutItemLegend::ensureModelIsInitialized()
const
379 if ( mDeferLegendModelInitialization )
382 mutableThis->mDeferLegendModelInitialization =
false;
383 mutableThis->setCustomLayerTree( mutableThis->mCustomLayerTree.release() );
389 QgsLegendRenderer res( mLegendModel.get(), mSettings );
391 QgsLegendFilterProxyModel *proxy =
new QgsLegendFilterProxyModel();
398 QgsExpressionContext expressionContext = mMap->createExpressionContext();
399 const QList<QgsMapLayer *> visibleLayers = mMap->layersToRender( &expressionContext );
406 if ( QgsProject *p = l->project() )
419 res.setProxyModel( proxy );
426 ensureModelIsInitialized();
427 return mLegendModel.get();
432 ensureModelIsInitialized();
433 return mLegendModel.get();
443 if ( mode == mSyncMode )
452 setCustomLayerTree(
nullptr );
471 std::unique_ptr< QgsLayerTree > customTree(
mLayout->project()->layerTreeRoot()->clone() );
473 QList<QgsMapLayer *> mapVisibleLayers;
479 mapVisibleLayers = mMap->layersToRender( &expressionContext );
486 mapVisibleLayers = p->layerTreeRoot()->checkedLayers();
493 filterNodeChildren = [mapVisibleLayers, mode, &filterNodeChildren](
QgsLayerTreeGroup *group ) {
497 const QList<QgsLayerTreeNode *> children = group->children();
502 group->removeChildNode( child );
516 group->removeChildNode( child );
520 group->removeChildNode( child );
526 filterNodeChildren( customTree.get() );
528 setCustomLayerTree( customTree.release() );
531void QgsLayoutItemLegend::nodeCustomPropertyChanged(
QgsLayerTreeNode *,
const QString &key )
533 if ( key ==
"cached_name"_L1 )
578 if ( mLegendFilterByMap == enabled )
581 mLegendFilterByMap = enabled;
588 mSettings.setTitle( t );
590 if (
mLayout &&
id().isEmpty() )
593 mLayout->itemsModel()->updateItemDisplayName(
this );
603 return mSettings.titleAlignment();
608 mSettings.setTitleAlignment( alignment );
613 return mSettings.rstyle( s );
618 return mSettings.style( s );
623 mSettings.setStyle( s,
style );
629 return mSettings.style( s ).font();
653 return mSettings.lineSpacing();
660 mSettings.setLineSpacing( spacing );
666 return mSettings.boxSpace();
671 mSettings.setBoxSpace( s );
676 return mSettings.columnSpace();
681 mSettings.setColumnSpace( s );
687 return mSettings.fontColor();
694 mSettings.setFontColor(
c );
700 return mSettings.symbolSize().width();
705 mSettings.setSymbolSize( QSizeF( w, mSettings.symbolSize().height() ) );
710 return mSettings.maximumSymbolSize();
715 mSettings.setMaximumSymbolSize( size );
720 return mSettings.minimumSymbolSize();
725 mSettings.setMinimumSymbolSize( size );
730 mSettings.setSymbolAlignment( alignment );
735 return mSettings.symbolAlignment();
740 return mSettings.symbolSize().height();
745 mSettings.setSymbolSize( QSizeF( mSettings.symbolSize().width(), h ) );
750 return mSettings.wmsLegendSize().width();
755 mSettings.setWmsLegendSize( QSizeF( w, mSettings.wmsLegendSize().height() ) );
760 return mSettings.wmsLegendSize().height();
764 mSettings.setWmsLegendSize( QSizeF( mSettings.wmsLegendSize().width(), h ) );
769 mSettings.setWrapChar( t );
774 return mSettings.wrapChar();
785 mSettings.setColumnCount(
c );
790 return mSettings.splitLayer();
795 mSettings.setSplitLayer( s );
800 return mSettings.equalColumnWidth();
805 mSettings.setEqualColumnWidth( s );
810 return mSettings.drawRasterStroke();
815 mSettings.setDrawRasterStroke( enabled );
820 return mSettings.rasterStrokeColor();
825 mSettings.setRasterStrokeColor( color );
830 return mSettings.rasterStrokeWidth();
835 mSettings.setRasterStrokeWidth( width );
840 return mSettings.autoWrapLinesAfter();
845 mSettings.setAutoWrapLinesAfter( length );
857 legendElem.setAttribute( u
"title"_s, mTitle );
858 legendElem.setAttribute( u
"titleAlignment"_s, QString::number(
static_cast< int >( mSettings.titleAlignment() ) ) );
859 legendElem.setAttribute( u
"columnCount"_s, QString::number( mColumnCount ) );
860 legendElem.setAttribute( u
"splitLayer"_s, QString::number( mSettings.splitLayer() ) );
861 legendElem.setAttribute( u
"equalColumnWidth"_s, QString::number( mSettings.equalColumnWidth() ) );
863 legendElem.setAttribute( u
"boxSpace"_s, QString::number( mSettings.boxSpace() ) );
864 legendElem.setAttribute( u
"columnSpace"_s, QString::number( mSettings.columnSpace() ) );
866 legendElem.setAttribute( u
"symbolWidth"_s, QString::number( mSettings.symbolSize().width() ) );
867 legendElem.setAttribute( u
"symbolHeight"_s, QString::number( mSettings.symbolSize().height() ) );
868 legendElem.setAttribute( u
"maxSymbolSize"_s, QString::number( mSettings.maximumSymbolSize() ) );
869 legendElem.setAttribute( u
"minSymbolSize"_s, QString::number( mSettings.minimumSymbolSize() ) );
871 legendElem.setAttribute( u
"symbolAlignment"_s, mSettings.symbolAlignment() );
873 legendElem.setAttribute( u
"symbolAlignment"_s, mSettings.symbolAlignment() );
875 legendElem.setAttribute( u
"rasterBorder"_s, mSettings.drawRasterStroke() );
877 legendElem.setAttribute( u
"rasterBorderWidth"_s, QString::number( mSettings.rasterStrokeWidth() ) );
879 if ( mSettings.autoWrapLinesAfter() > 0 )
881 legendElem.setAttribute( u
"autoWrapLinesAfter"_s, mSettings.autoWrapLinesAfter() );
884 legendElem.setAttribute( u
"wmsLegendWidth"_s, QString::number( mSettings.wmsLegendSize().width() ) );
885 legendElem.setAttribute( u
"wmsLegendHeight"_s, QString::number( mSettings.wmsLegendSize().height() ) );
886 legendElem.setAttribute( u
"wrapChar"_s, mSettings.wrapChar() );
888 legendElem.setAttribute( u
"resizeToContents"_s, mSizeToContents );
892 legendElem.setAttribute( u
"map_uuid"_s, mMap->uuid() );
895 if ( !mFilterByMapItems.empty() )
897 QDomElement filterByMapsElem = doc.createElement( u
"filterByMaps"_s );
902 QDomElement mapElem = doc.createElement( u
"map"_s );
903 mapElem.setAttribute( u
"uuid"_s, map->uuid() );
904 filterByMapsElem.appendChild( mapElem );
907 legendElem.appendChild( filterByMapsElem );
910 QDomElement legendStyles = doc.createElement( u
"styles"_s );
911 legendElem.appendChild( legendStyles );
919 if ( mCustomLayerTree )
922 mCustomLayerTree->writeXml( legendElem, context );
929 if ( mLegendFilterByMap )
931 legendElem.setAttribute( u
"legendFilterByMap"_s, u
"1"_s );
933 legendElem.setAttribute( u
"legendFilterByAtlas"_s, mFilterOutAtlas ? u
"1"_s : u
"0"_s );
941 mTitle = itemElem.attribute( u
"title"_s );
942 mSettings.setTitle( mTitle );
943 if ( !itemElem.attribute( u
"titleAlignment"_s ).isEmpty() )
945 mSettings.setTitleAlignment(
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( u
"titleAlignment"_s ).toInt() ) );
947 int colCount = itemElem.attribute( u
"columnCount"_s, u
"1"_s ).toInt();
950 mColumnCount = colCount;
951 mSettings.setColumnCount( mColumnCount );
952 mSettings.setSplitLayer( itemElem.attribute( u
"splitLayer"_s, u
"0"_s ).toInt() == 1 );
953 mSettings.setEqualColumnWidth( itemElem.attribute( u
"equalColumnWidth"_s, u
"0"_s ).toInt() == 1 );
955 const QDomNodeList stylesNodeList = itemElem.elementsByTagName( u
"styles"_s );
956 if ( !stylesNodeList.isEmpty() )
958 const QDomNode stylesNode = stylesNodeList.at( 0 );
959 for (
int i = 0; i < stylesNode.childNodes().size(); i++ )
961 const QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
963 style.readXml( styleElem, doc, context );
964 const QString name = styleElem.attribute( u
"name"_s );
966 if ( name ==
"title"_L1 )
968 else if ( name ==
"group"_L1 )
970 else if ( name ==
"subgroup"_L1 )
972 else if ( name ==
"symbol"_L1 )
974 else if ( name ==
"symbolLabel"_L1 )
983 if ( itemElem.hasAttribute( u
"fontColor"_s ) )
986 fontClr.setNamedColor( itemElem.attribute( u
"fontColor"_s, u
"#000000"_s ) );
994 mSettings.setBoxSpace( itemElem.attribute( u
"boxSpace"_s, u
"2.0"_s ).toDouble() );
995 mSettings.setColumnSpace( itemElem.attribute( u
"columnSpace"_s, u
"2.0"_s ).toDouble() );
997 mSettings.setSymbolSize( QSizeF( itemElem.attribute( u
"symbolWidth"_s, u
"7.0"_s ).toDouble(), itemElem.attribute( u
"symbolHeight"_s, u
"14.0"_s ).toDouble() ) );
998 mSettings.setSymbolAlignment(
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( u
"symbolAlignment"_s, QString::number( Qt::AlignLeft ) ).toInt() ) );
1000 mSettings.setMaximumSymbolSize( itemElem.attribute( u
"maxSymbolSize"_s, u
"0.0"_s ).toDouble() );
1001 mSettings.setMinimumSymbolSize( itemElem.attribute( u
"minSymbolSize"_s, u
"0.0"_s ).toDouble() );
1003 mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( u
"wmsLegendWidth"_s, u
"50"_s ).toDouble(), itemElem.attribute( u
"wmsLegendHeight"_s, u
"25"_s ).toDouble() ) );
1005 if ( itemElem.hasAttribute( u
"lineSpacing"_s ) )
1007 const double spacing = itemElem.attribute( u
"lineSpacing"_s, u
"1.0"_s ).toDouble();
1031 mSettings.setDrawRasterStroke( itemElem.attribute( u
"rasterBorder"_s, u
"1"_s ) !=
"0"_L1 );
1033 mSettings.setRasterStrokeWidth( itemElem.attribute( u
"rasterBorderWidth"_s, u
"0"_s ).toDouble() );
1035 mSettings.setAutoWrapLinesAfter( itemElem.attribute( u
"autoWrapLinesAfter"_s, u
"0"_s ).toDouble() );
1037 mSettings.setWrapChar( itemElem.attribute( u
"wrapChar"_s ) );
1039 mSizeToContents = itemElem.attribute( u
"resizeToContents"_s, u
"1"_s ) !=
"0"_L1;
1042 mLegendFilterByMap = itemElem.attribute( u
"legendFilterByMap"_s, u
"0"_s ).toInt();
1045 if ( !itemElem.attribute( u
"map_uuid"_s ).isEmpty() )
1047 mMapUuid = itemElem.attribute( u
"map_uuid"_s );
1050 mFilterByMapUuids.clear();
1052 const QDomElement filterByMapsElem = itemElem.firstChildElement( u
"filterByMaps"_s );
1053 if ( !filterByMapsElem.isNull() )
1055 QDomElement mapsElem = filterByMapsElem.firstChildElement( u
"map"_s );
1056 while ( !mapsElem.isNull() )
1058 mFilterByMapUuids << mapsElem.attribute( u
"uuid"_s );
1059 mapsElem = mapsElem.nextSiblingElement( u
"map"_s );
1062 else if ( !mMapUuid.isEmpty() )
1065 mFilterByMapUuids << mMapUuid;
1070 setupMapConnections( mMap,
false );
1073 mFilterOutAtlas = itemElem.attribute( u
"legendFilterByAtlas"_s, u
"0"_s ).toInt();
1076 QDomElement layerTreeElem = itemElem.firstChildElement( u
"layer-tree"_s );
1077 if ( layerTreeElem.isNull() )
1078 layerTreeElem = itemElem.firstChildElement( u
"layer-tree-group"_s );
1080 if ( !layerTreeElem.isNull() )
1084 tree->resolveReferences(
mLayout->project(),
true );
1085 setCustomLayerTree( tree.release() );
1090 setCustomLayerTree(
nullptr );
1099 if ( !
id().isEmpty() )
1105 QString text = mSettings.title();
1106 if ( text.isEmpty() )
1108 return tr(
"<Legend>" );
1110 if ( text.length() > 25 )
1112 return tr(
"%1…" ).arg( text.left( 25 ) );
1122 return blendMode() != QPainter::CompositionMode_SourceOver;
1127 return mEvaluatedOpacity < 1.0;
1130void QgsLayoutItemLegend::setupMapConnections(
QgsLayoutItemMap *map,
bool connectSlots )
1135 if ( !connectSlots )
1137 disconnect( map, &QObject::destroyed,
this, &QgsLayoutItemLegend::invalidateCurrentMap );
1146 connect( map, &QObject::destroyed,
this, &QgsLayoutItemLegend::invalidateCurrentMap );
1162 setupMapConnections( mMap,
false );
1169 setupMapConnections( mMap,
true );
1170 mapThemeChanged( mMap->themeToRender( mMap->createExpressionContext() ) );
1183 setupMapConnections( map,
false );
1186 mFilterByMapItems.clear();
1187 mFilterByMapItems.reserve( maps.size() );
1192 mFilterByMapItems.append( map );
1193 setupMapConnections( map,
true );
1202 QList<QgsLayoutItemMap *> res;
1203 res.reserve( mFilterByMapItems.size() );
1212void QgsLayoutItemLegend::invalidateCurrentMap()
1221 bool forceUpdate =
false;
1229 mSettings.setTitle( t );
1237 if ( ok && cols >= 0 )
1239 mSettings.setColumnCount( cols );
1247 if ( ok && width >= 0 )
1249 mSettings.setAutoWrapLinesAfter( width );
1263void QgsLayoutItemLegend::updateFilterByMapAndRedraw()
1268void QgsLayoutItemLegend::setModelStyleOverrides(
const QMap<QString, QString> &overrides )
1270 mLegendModel->setLayerStyleOverrides( overrides );
1271 if ( QgsLayerTree *rootGroup = mLegendModel->rootGroup() )
1273 const QList< QgsLayerTreeLayer * > layers = rootGroup->
findLayers();
1274 for ( QgsLayerTreeLayer *nodeLayer : std::as_const( layers ) )
1275 mLegendModel->refreshLayerLegend( nodeLayer );
1279void QgsLayoutItemLegend::clearLegendCachedData()
1281 std::function< void( QgsLayerTreeNode * ) > clearNodeCache;
1282 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 || ( mLegendFilterByMap && ( mMap || !mFilterByMapItems.empty() ) ) || mInAtlas || requiresFilteringBecauseOfRendererSetting();
1385 if ( hasValidFilter )
1387 const double dpi =
mLayout->renderContext().dpi();
1389 QSet< QgsLayoutItemMap * > linkedFilterMaps;
1390 if ( mLegendFilterByMap )
1394 linkedFilterMaps.insert( mMap );
1397 QgsMapSettings mapSettings;
1398 QgsGeometry filterGeometry;
1402 const QgsRectangle requestRectangle = mMap->requestedExtent();
1403 QSizeF size( requestRectangle.
width(), requestRectangle.
height() );
1405 mapSettings = mMap->mapSettings( requestRectangle, size, dpi,
true );
1409 else if ( !linkedFilterMaps.empty() )
1412 const QgsRectangle requestRectangle = ( *linkedFilterMaps.constBegin() )->requestedExtent();
1413 QSizeF size( requestRectangle.
width(), requestRectangle.
height() );
1415 mapSettings = ( *linkedFilterMaps.constBegin() )->mapSettings( requestRectangle, size, dpi,
true );
1422 const QgsGeometry atlasGeometry {
mLayout->reportContext().currentGeometry( mapSettings.
destinationCrs() ) };
1424 QgsLayerTreeFilterSettings filterSettings( mapSettings );
1426 QList<QgsMapLayer *> layersToClip;
1429 if ( !atlasGeometry.
isNull() && mMap->atlasClippingSettings()->enabled() )
1431 layersToClip = mMap->atlasClippingSettings()->layersToClip();
1432 for ( QgsMapLayer *layer : std::as_const( layersToClip ) )
1434 QList<QgsMapLayer *> mapLayers { filterSettings.mapSettings().layers(
true ) };
1435 mapLayers.removeAll( layer );
1436 filterSettings.mapSettings().setLayers( mapLayers );
1437 filterSettings.addVisibleExtentForLayer( layer, QgsReferencedGeometry( atlasGeometry, mapSettings.
destinationCrs() ) );
1442 if ( !linkedFilterMaps.empty() )
1457 catch ( QgsCsException & )
1462 const QList< QgsMapLayer * > layersForMap = map->
layersToRender();
1463 for ( QgsMapLayer *layer : layersForMap )
1465 if ( mInAtlas && !atlasGeometry.
isNull() )
1470 filterSettings.addVisibleExtentForLayer( layer, QgsReferencedGeometry( mapExtent, mapSettings.
destinationCrs() ) );
1477 if ( !filterGeometry.
isEmpty() )
1483 filterSettings.setLayerFilterExpressionsFromLayerTree( mLegendModel->rootGroup() );
1484 if ( !filterGeometry.
isNull() )
1486 filterSettings.setFilterPolygon( filterGeometry );
1493 mLegendModel->setFilterSettings( &filterSettings );
1497 mLegendModel->setFilterSettings(
nullptr );
1500 clearLegendCachedData();
1501 mForceResize =
true;
1511 mFilterOutAtlas = doFilter;
1516 return mFilterOutAtlas;
1519void QgsLayoutItemLegend::onAtlasFeature()
1523 mInAtlas = mFilterOutAtlas;
1527void QgsLayoutItemLegend::onAtlasEnded()
1541 context.
appendScope( mMap->createExpressionContext().popScope() );
1566 const QList<QgsLayerTreeNode *> childNodes = group->
children();
1572 if ( !visit( nodeGroup ) )
1584 const QList<QgsLayerTreeModelLegendNode *> legendNodes = mLegendModel->layerLegendNodes( nodeLayer );
1589 if ( !symbolNode->patchShape().isNull() )
1601 return visit(
model()->rootGroup() );
1606 return mLegendModel->hitTestInProgress();
1610bool QgsLayoutItemLegend::requiresFilteringBecauseOfRendererSetting()
1618 if ( !mapLayer || !mapLayer->
isValid() )
1620 if (
QgsRasterLayer *rl = qobject_cast<QgsRasterLayer *>( mapLayer ) )
1627 else if ( QgsMeshLayer *ml = qobject_cast<QgsMeshLayer *>( mapLayer ) )
1629 const QgsMeshDatasetIndex activeDatasetIndex = ml->staticScalarDatasetIndex();
1631 if ( activeDatasetIndex.
isValid() )
1633 QgsMeshRendererScalarSettings scalarRendererSettings = ml->rendererSettings().scalarSettings( activeDatasetIndex.
group() );
1650 , mLayoutLegend( layout )
1660 , mLayoutLegend( layout )
1674 if ( nodeLayer && ( role == Qt::DisplayRole || role == Qt::EditRole ) )
1676 QString name = node->
customProperty( u
"cached_name"_s ).toString();
1677 if ( !name.isEmpty() )
1683 name = nodeLayer->
customProperty( u
"legend/title-label"_s ).toString();
1684 if ( name.isEmpty() )
1685 name = nodeLayer->
name();
1686 if ( name.isEmpty() )
1687 name = node->
customProperty( u
"legend/title-label"_s ).toString();
1688 if ( name.isEmpty() )
1689 name = node->
name();
1690 if ( nodeLayer->
customProperty( u
"showFeatureCount"_s, 0 ).toInt() )
1716 if ( !
mLegend.contains( nodeLayer ) )
1717 return QList<QgsLayerTreeModelLegendNode *>();
1720 QList<QgsLayerTreeModelLegendNode *> lst(
data.activeNodes );
1721 if ( !skipNodeEmbeddedInParent &&
data.embeddedNodeInParent )
1722 lst.prepend(
data.embeddedNodeInParent );
1731void 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.