46#include <QDomDocument>
50#include "moc_qgslayoutitemlegend.cpp"
64 mIsDefaultLegend = isDefault;
72bool QgsLegendFilterProxyModel::layerShown(
QgsMapLayer *layer )
const
94 connect( &
layout->atlasComposition(), &QgsAtlasComposition::renderEnded,
this, &QgsLayoutItemLegend::onAtlasEnded );
97 mTitle = mSettings.title();
103 emit backgroundTaskCountChanged( 0 );
150 const QPointF oldPos = pos();
152 ensureModelIsInitialized();
154 if ( mFilterAskedForUpdate )
156 mFilterAskedForUpdate =
false;
157 doUpdateFilterByMap();
160 const int dpi = painter->device()->logicalDpiX();
161 const double dotsPerMM = dpi / 25.4;
168 mSettings.setDpi( dpi );
180 const QSizeF mapSizePixels = QSizeF( mMap->rect().width() * dotsPerMM, mMap->rect().height() * dotsPerMM );
183 const QgsMapSettings ms = mMap->mapSettings( mapExtent, mapSizePixels, dpi,
false );
187 mSettings.setMapScale( ms.
scale() );
190 mInitialMapScaleCalculated =
true;
193 legendRenderer.
setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() );
196 if ( mSizeToContents )
202 const QSizeF size = legendRenderer.
minimumSize( &context );
205 mForceResize =
false;
211 else if ( size.height() > rect().height() || size.width() > rect().width() )
214 QSizeF targetSize = rect().size();
215 if ( size.height() > targetSize.height() )
216 targetSize.setHeight( size.height() );
217 if ( size.width() > targetSize.width() )
218 targetSize.setWidth( size.width() );
232 painter->translate( pos() - oldPos );
239 if ( !mMapUuid.isEmpty() )
241 setLinkedMap( qobject_cast< QgsLayoutItemMap * >(
mLayout->itemByUuid( mMapUuid,
true ) ) );
244 if ( !mFilterByMapUuids.isEmpty() )
246 QList< QgsLayoutItemMap * > maps;
247 maps.reserve( mFilterByMapUuids.size() );
248 for (
const QString &
uuid : std::as_const( mFilterByMapUuids ) )
262 clearLegendCachedData();
268 clearLegendCachedData();
287 painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
289 if ( !mSizeToContents )
292 const QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() );
293 painter->setClipRect( thisPaintRect );
300 mSettings.setDpi(
mLayout->renderContext().dpi() );
312 if ( !mSizeToContents )
315 if ( !mInitialMapScaleCalculated )
329 const QSizeF size = legendRenderer.
minimumSize( &context );
330 QgsDebugMsgLevel( QStringLiteral(
"width = %1 height = %2" ).arg( size.width() ).arg( size.height() ), 2 );
331 if ( size.isValid() )
341 mSizeToContents = enabled;
346 return mSizeToContents;
349void QgsLayoutItemLegend::setCustomLayerTree(
QgsLayerTree *rootGroup )
351 if ( !mDeferLegendModelInitialization )
353 mLegendModel->setRootGroup( rootGroup ? rootGroup : (
mLayout ?
mLayout->project()->layerTreeRoot() :
nullptr ) );
356 mCustomLayerTree.reset( rootGroup );
359void QgsLayoutItemLegend::ensureModelIsInitialized()
const
361 if ( mDeferLegendModelInitialization )
364 mutableThis->mDeferLegendModelInitialization =
false;
365 mutableThis->setCustomLayerTree( mutableThis->mCustomLayerTree.release() );
371 QgsLegendRenderer res( mLegendModel.get(), mSettings );
373 QgsLegendFilterProxyModel *proxy =
new QgsLegendFilterProxyModel();
375 res.setProxyModel( proxy );
382 ensureModelIsInitialized();
383 return mLegendModel.get();
388 ensureModelIsInitialized();
389 return mLegendModel.get();
399 setCustomLayerTree(
nullptr );
403 std::unique_ptr< QgsLayerTree > customTree(
mLayout->project()->layerTreeRoot()->clone() );
412 const QList<QgsLayerTreeNode *> children = group->children();
417 group->removeChildNode( child );
431 group->removeChildNode( child );
437 filterNodeChildren( customTree.get() );
439 setCustomLayerTree( customTree.release() );
446void QgsLayoutItemLegend::nodeCustomPropertyChanged(
QgsLayerTreeNode *,
const QString &key )
448 if ( key == QLatin1String(
"cached_name" ) )
461 return !mCustomLayerTree;
466 if ( mLegendFilterByMap == enabled )
469 mLegendFilterByMap = enabled;
476 mSettings.setTitle( t );
478 if (
mLayout &&
id().isEmpty() )
481 mLayout->itemsModel()->updateItemDisplayName(
this );
491 return mSettings.titleAlignment();
496 mSettings.setTitleAlignment( alignment );
501 return mSettings.rstyle( s );
506 return mSettings.style( s );
511 mSettings.setStyle( s,
style );
517 return mSettings.style( s ).font();
541 return mSettings.lineSpacing();
548 mSettings.setLineSpacing( spacing );
554 return mSettings.boxSpace();
559 mSettings.setBoxSpace( s );
564 return mSettings.columnSpace();
569 mSettings.setColumnSpace( s );
575 return mSettings.fontColor();
582 mSettings.setFontColor(
c );
588 return mSettings.symbolSize().width();
593 mSettings.setSymbolSize( QSizeF( w, mSettings.symbolSize().height() ) );
598 return mSettings.maximumSymbolSize();
603 mSettings.setMaximumSymbolSize( size );
608 return mSettings.minimumSymbolSize();
613 mSettings.setMinimumSymbolSize( size );
618 mSettings.setSymbolAlignment( alignment );
623 return mSettings.symbolAlignment();
628 return mSettings.symbolSize().height();
633 mSettings.setSymbolSize( QSizeF( mSettings.symbolSize().width(), h ) );
638 return mSettings.wmsLegendSize().width();
643 mSettings.setWmsLegendSize( QSizeF( w, mSettings.wmsLegendSize().height() ) );
648 return mSettings.wmsLegendSize().height();
652 mSettings.setWmsLegendSize( QSizeF( mSettings.wmsLegendSize().width(), h ) );
657 mSettings.setWrapChar( t );
662 return mSettings.wrapChar();
673 mSettings.setColumnCount(
c );
678 return mSettings.splitLayer();
683 mSettings.setSplitLayer( s );
688 return mSettings.equalColumnWidth();
693 mSettings.setEqualColumnWidth( s );
698 return mSettings.drawRasterStroke();
703 mSettings.setDrawRasterStroke( enabled );
708 return mSettings.rasterStrokeColor();
713 mSettings.setRasterStrokeColor( color );
718 return mSettings.rasterStrokeWidth();
723 mSettings.setRasterStrokeWidth( width );
728 return mSettings.autoWrapLinesAfter();
733 mSettings.setAutoWrapLinesAfter( length );
746 legendElem.setAttribute( QStringLiteral(
"title" ), mTitle );
747 legendElem.setAttribute( QStringLiteral(
"titleAlignment" ), QString::number(
static_cast< int >( mSettings.titleAlignment() ) ) );
748 legendElem.setAttribute( QStringLiteral(
"columnCount" ), QString::number( mColumnCount ) );
749 legendElem.setAttribute( QStringLiteral(
"splitLayer" ), QString::number( mSettings.splitLayer() ) );
750 legendElem.setAttribute( QStringLiteral(
"equalColumnWidth" ), QString::number( mSettings.equalColumnWidth() ) );
752 legendElem.setAttribute( QStringLiteral(
"boxSpace" ), QString::number( mSettings.boxSpace() ) );
753 legendElem.setAttribute( QStringLiteral(
"columnSpace" ), QString::number( mSettings.columnSpace() ) );
755 legendElem.setAttribute( QStringLiteral(
"symbolWidth" ), QString::number( mSettings.symbolSize().width() ) );
756 legendElem.setAttribute( QStringLiteral(
"symbolHeight" ), QString::number( mSettings.symbolSize().height() ) );
757 legendElem.setAttribute( QStringLiteral(
"maxSymbolSize" ), QString::number( mSettings.maximumSymbolSize() ) );
758 legendElem.setAttribute( QStringLiteral(
"minSymbolSize" ), QString::number( mSettings.minimumSymbolSize() ) );
760 legendElem.setAttribute( QStringLiteral(
"symbolAlignment" ), mSettings.symbolAlignment() );
762 legendElem.setAttribute( QStringLiteral(
"symbolAlignment" ), mSettings.symbolAlignment() );
764 legendElem.setAttribute( QStringLiteral(
"rasterBorder" ), mSettings.drawRasterStroke() );
766 legendElem.setAttribute( QStringLiteral(
"rasterBorderWidth" ), QString::number( mSettings.rasterStrokeWidth() ) );
768 if ( mSettings.autoWrapLinesAfter() > 0 )
770 legendElem.setAttribute( QStringLiteral(
"autoWrapLinesAfter" ), mSettings.autoWrapLinesAfter() );
773 legendElem.setAttribute( QStringLiteral(
"wmsLegendWidth" ), QString::number( mSettings.wmsLegendSize().width() ) );
774 legendElem.setAttribute( QStringLiteral(
"wmsLegendHeight" ), QString::number( mSettings.wmsLegendSize().height() ) );
775 legendElem.setAttribute( QStringLiteral(
"wrapChar" ), mSettings.wrapChar() );
777 legendElem.setAttribute( QStringLiteral(
"resizeToContents" ), mSizeToContents );
781 legendElem.setAttribute( QStringLiteral(
"map_uuid" ), mMap->uuid() );
784 if ( !mFilterByMapItems.empty() )
786 QDomElement filterByMapsElem = doc.createElement( QStringLiteral(
"filterByMaps" ) );
791 QDomElement mapElem = doc.createElement( QStringLiteral(
"map" ) );
792 mapElem.setAttribute( QStringLiteral(
"uuid" ), map->uuid() );
793 filterByMapsElem.appendChild( mapElem );
796 legendElem.appendChild( filterByMapsElem );
799 QDomElement legendStyles = doc.createElement( QStringLiteral(
"styles" ) );
800 legendElem.appendChild( legendStyles );
808 if ( mCustomLayerTree )
811 mCustomLayerTree->writeXml( legendElem, context );
814 if ( mLegendFilterByMap )
816 legendElem.setAttribute( QStringLiteral(
"legendFilterByMap" ), QStringLiteral(
"1" ) );
818 legendElem.setAttribute( QStringLiteral(
"legendFilterByAtlas" ), mFilterOutAtlas ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
826 mTitle = itemElem.attribute( QStringLiteral(
"title" ) );
827 mSettings.setTitle( mTitle );
828 if ( !itemElem.attribute( QStringLiteral(
"titleAlignment" ) ).isEmpty() )
830 mSettings.setTitleAlignment(
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( QStringLiteral(
"titleAlignment" ) ).toInt() ) );
832 int colCount = itemElem.attribute( QStringLiteral(
"columnCount" ), QStringLiteral(
"1" ) ).toInt();
833 if ( colCount < 1 ) colCount = 1;
834 mColumnCount = colCount;
835 mSettings.setColumnCount( mColumnCount );
836 mSettings.setSplitLayer( itemElem.attribute( QStringLiteral(
"splitLayer" ), QStringLiteral(
"0" ) ).toInt() == 1 );
837 mSettings.setEqualColumnWidth( itemElem.attribute( QStringLiteral(
"equalColumnWidth" ), QStringLiteral(
"0" ) ).toInt() == 1 );
839 const QDomNodeList stylesNodeList = itemElem.elementsByTagName( QStringLiteral(
"styles" ) );
840 if ( !stylesNodeList.isEmpty() )
842 const QDomNode stylesNode = stylesNodeList.at( 0 );
843 for (
int i = 0; i < stylesNode.childNodes().size(); i++ )
845 const QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
847 style.readXml( styleElem, doc, context );
848 const QString name = styleElem.attribute( QStringLiteral(
"name" ) );
861 if ( itemElem.hasAttribute( QStringLiteral(
"fontColor" ) ) )
864 fontClr.setNamedColor( itemElem.attribute( QStringLiteral(
"fontColor" ), QStringLiteral(
"#000000" ) ) );
872 mSettings.setBoxSpace( itemElem.attribute( QStringLiteral(
"boxSpace" ), QStringLiteral(
"2.0" ) ).toDouble() );
873 mSettings.setColumnSpace( itemElem.attribute( QStringLiteral(
"columnSpace" ), QStringLiteral(
"2.0" ) ).toDouble() );
875 mSettings.setSymbolSize( QSizeF( itemElem.attribute( QStringLiteral(
"symbolWidth" ), QStringLiteral(
"7.0" ) ).toDouble(), itemElem.attribute( QStringLiteral(
"symbolHeight" ), QStringLiteral(
"14.0" ) ).toDouble() ) );
876 mSettings.setSymbolAlignment(
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( QStringLiteral(
"symbolAlignment" ), QString::number( Qt::AlignLeft ) ).toInt() ) );
878 mSettings.setMaximumSymbolSize( itemElem.attribute( QStringLiteral(
"maxSymbolSize" ), QStringLiteral(
"0.0" ) ).toDouble() );
879 mSettings.setMinimumSymbolSize( itemElem.attribute( QStringLiteral(
"minSymbolSize" ), QStringLiteral(
"0.0" ) ).toDouble() );
881 mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( QStringLiteral(
"wmsLegendWidth" ), QStringLiteral(
"50" ) ).toDouble(), itemElem.attribute( QStringLiteral(
"wmsLegendHeight" ), QStringLiteral(
"25" ) ).toDouble() ) );
883 if ( itemElem.hasAttribute( QStringLiteral(
"lineSpacing" ) ) )
885 const double spacing = itemElem.attribute( QStringLiteral(
"lineSpacing" ), QStringLiteral(
"1.0" ) ).toDouble();
909 mSettings.setDrawRasterStroke( itemElem.attribute( QStringLiteral(
"rasterBorder" ), QStringLiteral(
"1" ) ) != QLatin1String(
"0" ) );
910 mSettings.setRasterStrokeColor(
QgsColorUtils::colorFromString( itemElem.attribute( QStringLiteral(
"rasterBorderColor" ), QStringLiteral(
"0,0,0" ) ) ) );
911 mSettings.setRasterStrokeWidth( itemElem.attribute( QStringLiteral(
"rasterBorderWidth" ), QStringLiteral(
"0" ) ).toDouble() );
913 mSettings.setAutoWrapLinesAfter( itemElem.attribute( QStringLiteral(
"autoWrapLinesAfter" ), QStringLiteral(
"0" ) ).toDouble() );
915 mSettings.setWrapChar( itemElem.attribute( QStringLiteral(
"wrapChar" ) ) );
917 mSizeToContents = itemElem.attribute( QStringLiteral(
"resizeToContents" ), QStringLiteral(
"1" ) ) != QLatin1String(
"0" );
920 mLegendFilterByMap = itemElem.attribute( QStringLiteral(
"legendFilterByMap" ), QStringLiteral(
"0" ) ).toInt();
923 if ( !itemElem.attribute( QStringLiteral(
"map_uuid" ) ).isEmpty() )
925 mMapUuid = itemElem.attribute( QStringLiteral(
"map_uuid" ) );
928 mFilterByMapUuids.clear();
930 const QDomElement filterByMapsElem = itemElem.firstChildElement( QStringLiteral(
"filterByMaps" ) );
931 if ( !filterByMapsElem.isNull() )
933 QDomElement mapsElem = filterByMapsElem.firstChildElement( QStringLiteral(
"map" ) );
934 while ( !mapsElem.isNull() )
936 mFilterByMapUuids << mapsElem.attribute( QStringLiteral(
"uuid" ) );
937 mapsElem = mapsElem.nextSiblingElement( QStringLiteral(
"map" ) );
940 else if ( !mMapUuid.isEmpty() )
943 mFilterByMapUuids << mMapUuid;
948 setupMapConnections( mMap,
false );
951 mFilterOutAtlas = itemElem.attribute( QStringLiteral(
"legendFilterByAtlas" ), QStringLiteral(
"0" ) ).toInt();
954 QDomElement layerTreeElem = itemElem.firstChildElement( QStringLiteral(
"layer-tree" ) );
955 if ( layerTreeElem.isNull() )
956 layerTreeElem = itemElem.firstChildElement( QStringLiteral(
"layer-tree-group" ) );
958 if ( !layerTreeElem.isNull() )
962 tree->resolveReferences(
mLayout->project(),
true );
963 setCustomLayerTree( tree.release() );
966 setCustomLayerTree(
nullptr );
973 if ( !
id().isEmpty() )
979 QString text = mSettings.title();
980 if ( text.isEmpty() )
982 return tr(
"<Legend>" );
984 if ( text.length() > 25 )
986 return tr(
"%1…" ).arg( text.left( 25 ) );
996 return blendMode() != QPainter::CompositionMode_SourceOver;
1001 return mEvaluatedOpacity < 1.0;
1004void QgsLayoutItemLegend::setupMapConnections(
QgsLayoutItemMap *map,
bool connectSlots )
1009 if ( !connectSlots )
1011 disconnect( map, &QObject::destroyed,
this, &QgsLayoutItemLegend::invalidateCurrentMap );
1020 connect( map, &QObject::destroyed,
this, &QgsLayoutItemLegend::invalidateCurrentMap );
1036 setupMapConnections( mMap,
false );
1043 setupMapConnections( mMap,
true );
1044 mapThemeChanged( mMap->themeToRender( mMap->createExpressionContext() ) );
1057 setupMapConnections( map,
false );
1060 mFilterByMapItems.clear();
1061 mFilterByMapItems.reserve( maps.size() );
1066 mFilterByMapItems.append( map );
1067 setupMapConnections( map,
true );
1076 QList<QgsLayoutItemMap *> res;
1077 res.reserve( mFilterByMapItems.size() );
1086void QgsLayoutItemLegend::invalidateCurrentMap()
1095 bool forceUpdate =
false;
1103 mSettings.setTitle( t );
1111 if ( ok && cols >= 0 )
1113 mSettings.setColumnCount( cols );
1121 if ( ok && width >= 0 )
1123 mSettings.setAutoWrapLinesAfter( width );
1137void QgsLayoutItemLegend::updateFilterByMapAndRedraw()
1142void QgsLayoutItemLegend::setModelStyleOverrides(
const QMap<QString, QString> &overrides )
1144 mLegendModel->setLayerStyleOverrides( overrides );
1145 if ( QgsLayerTree *rootGroup = mLegendModel->rootGroup() )
1147 const QList< QgsLayerTreeLayer * > layers = rootGroup->
findLayers();
1148 for ( QgsLayerTreeLayer *nodeLayer : std::as_const( layers ) )
1149 mLegendModel->refreshLayerLegend( nodeLayer );
1153void QgsLayoutItemLegend::clearLegendCachedData()
1155 std::function< void( QgsLayerTreeNode * ) > clearNodeCache;
1156 clearNodeCache = [&]( QgsLayerTreeNode * node )
1158 mLegendModel->clearCachedData( node );
1162 const QList< QgsLayerTreeNode * > children = group->
children();
1163 for ( QgsLayerTreeNode *child : children )
1165 clearNodeCache( child );
1170 if ( QgsLayerTree *rootGroup = mLegendModel->rootGroup() )
1172 clearNodeCache( rootGroup );
1176void QgsLayoutItemLegend::mapLayerStyleOverridesChanged()
1182 if ( mLegendFilterByMap )
1190 setModelStyleOverrides( mMap->layerStyleOverrides() );
1198void QgsLayoutItemLegend::mapThemeChanged(
const QString &theme )
1200 if ( mThemeName == theme )
1221 mFilterAskedForUpdate =
true;
1227void QgsLayoutItemLegend::doUpdateFilterByMap()
1237 if ( mMap && !mThemeName.isEmpty() )
1240 const QMap<QString, QString> overrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
1241 setModelStyleOverrides( overrides );
1245 mLegendModel->setLayerStyleOverrides( mMap->layerStyleOverrides() );
1249 mLegendModel->setLayerStyleOverrides( QMap<QString, QString>() );
1258 const bool hasValidFilter = filterByExpression
1259 || ( mLegendFilterByMap && ( mMap || !mFilterByMapItems.empty() ) )
1262 if ( hasValidFilter )
1264 const double dpi =
mLayout->renderContext().dpi();
1266 QSet< QgsLayoutItemMap * > linkedFilterMaps;
1267 if ( mLegendFilterByMap )
1271 linkedFilterMaps.insert( mMap );
1274 QgsMapSettings mapSettings;
1275 QgsGeometry filterGeometry;
1279 const QgsRectangle requestRectangle = mMap->requestedExtent();
1280 QSizeF size( requestRectangle.
width(), requestRectangle.
height() );
1282 mapSettings = mMap->mapSettings( requestRectangle, size, dpi,
true );
1286 else if ( !linkedFilterMaps.empty() )
1289 const QgsRectangle requestRectangle = ( *linkedFilterMaps.constBegin() )->requestedExtent();
1290 QSizeF size( requestRectangle.
width(), requestRectangle.
height() );
1292 mapSettings = ( *linkedFilterMaps.constBegin() )->mapSettings( requestRectangle, size, dpi,
true );
1299 const QgsGeometry atlasGeometry {
mLayout->reportContext().currentGeometry( mapSettings.
destinationCrs() ) };
1301 QgsLayerTreeFilterSettings filterSettings( mapSettings );
1303 QList<QgsMapLayer *> layersToClip;
1306 if ( !atlasGeometry.
isNull() && mMap->atlasClippingSettings()->enabled() )
1308 layersToClip = mMap->atlasClippingSettings()->layersToClip();
1309 for ( QgsMapLayer *layer : std::as_const( layersToClip ) )
1311 QList<QgsMapLayer *> mapLayers { filterSettings.mapSettings().layers(
true ) };
1312 mapLayers.removeAll( layer );
1313 filterSettings.mapSettings().setLayers( mapLayers );
1314 filterSettings.addVisibleExtentForLayer( layer, QgsReferencedGeometry( atlasGeometry, mapSettings.
destinationCrs() ) );
1319 if ( !linkedFilterMaps.empty() )
1335 catch ( QgsCsException & )
1340 const QList< QgsMapLayer * > layersForMap = map->
layersToRender();
1341 for ( QgsMapLayer *layer : layersForMap )
1343 if ( mInAtlas && !atlasGeometry.
isNull() )
1348 filterSettings.addVisibleExtentForLayer( layer, QgsReferencedGeometry( mapExtent, mapSettings.
destinationCrs() ) );
1355 if ( !filterGeometry.
isEmpty() )
1361 filterSettings.setLayerFilterExpressionsFromLayerTree( mLegendModel->rootGroup() );
1362 if ( !filterGeometry.
isNull() )
1364 filterSettings.setFilterPolygon( filterGeometry );
1371 mLegendModel->setFilterSettings( &filterSettings );
1375 mLegendModel->setFilterSettings(
nullptr );
1378 clearLegendCachedData();
1379 mForceResize =
true;
1389 mFilterOutAtlas = doFilter;
1394 return mFilterOutAtlas;
1397void QgsLayoutItemLegend::onAtlasFeature()
1401 mInAtlas = mFilterOutAtlas;
1405void QgsLayoutItemLegend::onAtlasEnded()
1419 context.
appendScope( mMap->createExpressionContext().popScope() );
1445 const QList<QgsLayerTreeNode *> childNodes = group->
children();
1451 if ( !visit( nodeGroup ) )
1463 const QList<QgsLayerTreeModelLegendNode *> legendNodes = mLegendModel->layerLegendNodes( nodeLayer );
1468 if ( !symbolNode->patchShape().isNull() )
1480 return visit(
model()->rootGroup( ) );
1485 return mLegendModel->hitTestInProgress();
1493 , mLayoutLegend( layout )
1503 , mLayoutLegend( layout )
1517 if ( nodeLayer && ( role == Qt::DisplayRole || role == Qt::EditRole ) )
1519 QString name = node->
customProperty( QStringLiteral(
"cached_name" ) ).toString();
1520 if ( !name.isEmpty() )
1526 name = nodeLayer->
customProperty( QStringLiteral(
"legend/title-label" ) ).toString();
1527 if ( name.isEmpty() )
1528 name = nodeLayer->
name();
1529 if ( name.isEmpty() )
1530 name = node->
customProperty( QStringLiteral(
"legend/title-label" ) ).toString();
1531 if ( name.isEmpty() )
1532 name = node->
name();
1533 if ( nodeLayer->
customProperty( QStringLiteral(
"showFeatureCount" ), 0 ).toInt() )
1537 name += QStringLiteral(
" [%1]" ).arg( vlayer->
featureCount() );
1559 if ( !
mLegend.contains( nodeLayer ) )
1560 return QList<QgsLayerTreeModelLegendNode *>();
1563 QList<QgsLayerTreeModelLegendNode *> lst(
data.activeNodes );
1564 if ( !skipNodeEmbeddedInParent &&
data.embeddedNodeInParent )
1565 lst.prepend(
data.embeddedNodeInParent );
1574void 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).
@ SkipVisibilityCheck
If set, the standard visibility check should be skipped.
@ ExcludeByDefault
If set, the layer should not be included in legends by default, and must be manually added by a user.
@ 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...
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.
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.
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.
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.
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...
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 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 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...
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.
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
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.
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
#define Q_NOWARN_DEPRECATED_POP
#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.