QGIS API Documentation 3.28.14-Firenze (exported)
Loading...
Searching...
No Matches
qgslayoutitemlegend.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgslayoutitemlegend.cpp
3 -----------------------
4 begin : October 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17#include <limits>
18
19#include "qgslayoutitemlegend.h"
21#include "qgslayoutitemmap.h"
22#include "qgslayout.h"
23#include "qgslayoutmodel.h"
24#include "qgslayertree.h"
25#include "qgslayertreemodel.h"
26#include "qgslegendrenderer.h"
27#include "qgslegendstyle.h"
28#include "qgslogger.h"
29#include "qgsmapsettings.h"
30#include "qgsproject.h"
31#include "qgssymbollayerutils.h"
32#include "qgslayertreeutils.h"
33#include "qgslayoututils.h"
36#include <QDomDocument>
37#include <QDomElement>
38#include <QPainter>
40
42 : QgsLayoutItem( layout )
43 , mLegendModel( new QgsLegendModel( layout->project()->layerTreeRoot(), this ) )
44{
45#if 0 //no longer required?
46 connect( &layout->atlasComposition(), &QgsAtlasComposition::renderEnded, this, &QgsLayoutItemLegend::onAtlasEnded );
47#endif
48
49 mTitle = mSettings.title();
50
51 // Connect to the main layertreeroot.
52 // It serves in "auto update mode" as a medium between the main app legend and this one
53 connect( mLayout->project()->layerTreeRoot(), &QgsLayerTreeNode::customPropertyChanged, this, &QgsLayoutItemLegend::nodeCustomPropertyChanged );
54
55 // If project colors change, we need to redraw legend, as legend symbols may rely on project colors
56 connect( mLayout->project(), &QgsProject::projectColorsChanged, this, [ = ]
57 {
58 invalidateCache();
59 update();
60 } );
61 connect( mLegendModel.get(), &QgsLegendModel::refreshLegend, this, [ = ]
62 {
63 // NOTE -- we do NOT connect to ::refresh here, as we don't want to trigger the call to onAtlasFeature() which sets mFilterAskedForUpdate to true,
64 // causing an endless loop.
65
66 // TODO -- the call to QgsLayoutItem::refresh() is probably NOT required!
67 QgsLayoutItem::refresh();
68
69 // (this one is definitely required)
70 clearLegendCachedData();
71 } );
72}
73
78
83
85{
86 return QgsApplication::getThemeIcon( QStringLiteral( "/mLayoutItemLegend.svg" ) );
87}
88
89QgsLayoutItem::Flags QgsLayoutItemLegend::itemFlags() const
90{
92}
93
94void QgsLayoutItemLegend::paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget )
95{
96 if ( !painter )
97 return;
98
99 if ( mFilterAskedForUpdate )
100 {
101 mFilterAskedForUpdate = false;
102 doUpdateFilterByMap();
103 }
104
105 const int dpi = painter->device()->logicalDpiX();
106 const double dotsPerMM = dpi / 25.4;
107
108 if ( mLayout )
109 {
111 // no longer required, but left set for api stability
113 mSettings.setDpi( dpi );
115 }
116 if ( mMap && mLayout )
117 {
119 // no longer required, but left set for api stability
120 mSettings.setMmPerMapUnit( mLayout->convertFromLayoutUnits( mMap->mapUnitsToLayoutUnits(), QgsUnitTypes::LayoutMillimeters ).length() );
122
123 // use a temporary QgsMapSettings to find out real map scale
124 const QSizeF mapSizePixels = QSizeF( mMap->rect().width() * dotsPerMM, mMap->rect().height() * dotsPerMM );
125 const QgsRectangle mapExtent = mMap->extent();
126
127 const QgsMapSettings ms = mMap->mapSettings( mapExtent, mapSizePixels, dpi, false );
128
129 // no longer required, but left set for api stability
131 mSettings.setMapScale( ms.scale() );
133 }
134 mInitialMapScaleCalculated = true;
135
136 QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
137 legendRenderer.setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() );
138
139 const QPointF oldPos = pos();
140
141 //adjust box if width or height is too small
142 if ( mSizeToContents )
143 {
144 QgsRenderContext context = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, painter )
146
147 const QSizeF size = legendRenderer.minimumSize( &context );
148 if ( mForceResize )
149 {
150 mForceResize = false;
151
152 //set new rect, respecting position mode and data defined size/position
153 const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
154 attemptResize( newSize );
155 }
156 else if ( size.height() > rect().height() || size.width() > rect().width() )
157 {
158 //need to resize box
159 QSizeF targetSize = rect().size();
160 if ( size.height() > targetSize.height() )
161 targetSize.setHeight( size.height() );
162 if ( size.width() > targetSize.width() )
163 targetSize.setWidth( size.width() );
164
165 const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( targetSize, sizeWithUnits().units() );
166 //set new rect, respecting position mode and data defined size/position
167 attemptResize( newSize );
168 }
169 }
170
171 // attemptResize may change the legend position and would call setPos
172 // BUT the position is actually changed for the next draw, so we need to translate of the difference
173 // between oldPos and newPos
174 // the issue doesn't appear in desktop rendering but only in export because in the first one,
175 // Qt triggers a redraw on position change
176 painter->save();
177 painter->translate( pos() - oldPos );
178 QgsLayoutItem::paint( painter, itemStyle, pWidget );
179 painter->restore();
180}
181
183{
184 if ( !mMapUuid.isEmpty() )
185 {
186 setLinkedMap( qobject_cast< QgsLayoutItemMap * >( mLayout->itemByUuid( mMapUuid, true ) ) );
187 }
188}
189
191{
193 clearLegendCachedData();
194 onAtlasFeature();
195}
196
198{
199 clearLegendCachedData();
201}
202
204{
205 QPainter *painter = context.renderContext().painter();
206
207 QgsRenderContext rc = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, painter, context.renderContext().scaleFactor() * 25.4 )
209
211
212 const QgsScopedQPainterState painterState( painter );
213
214 // painter is scaled to dots, so scale back to layout units
215 painter->scale( rc.scaleFactor(), rc.scaleFactor() );
216
217 painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
218
219 if ( !mSizeToContents )
220 {
221 // set a clip region to crop out parts of legend which don't fit
222 const QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() );
223 painter->setClipRect( thisPaintRect );
224 }
225
226 if ( mLayout )
227 {
228 // no longer required, but left for API compatibility
230 mSettings.setDpi( mLayout->renderContext().dpi() );
232 }
233
234
235
236
237 QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
238 legendRenderer.setLegendSize( rect().size() );
239
240 legendRenderer.drawLegend( rc );
241}
242
244{
245 if ( !mSizeToContents )
246 return;
247
248 if ( !mInitialMapScaleCalculated )
249 {
250 // this is messy - but until we have painted the item we have no knowledge of the current DPI
251 // and so cannot correctly calculate the map scale. This results in incorrect size calculations
252 // for marker symbols with size in map units, causing the legends to initially expand to huge
253 // sizes if we attempt to calculate the box size first.
254 return;
255 }
256
257 QgsRenderContext context = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, nullptr ) :
259
260 QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
261 const QSizeF size = legendRenderer.minimumSize( &context );
262 QgsDebugMsg( QStringLiteral( "width = %1 height = %2" ).arg( size.width() ).arg( size.height() ) );
263 if ( size.isValid() )
264 {
265 const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
266 //set new rect, respecting position mode and data defined size/position
267 attemptResize( newSize );
268 }
269}
270
272{
273 mSizeToContents = enabled;
274}
275
277{
278 return mSizeToContents;
279}
280
281void QgsLayoutItemLegend::setCustomLayerTree( QgsLayerTree *rootGroup )
282{
283 mLegendModel->setRootGroup( rootGroup ? rootGroup : ( mLayout ? mLayout->project()->layerTreeRoot() : nullptr ) );
284
285 mCustomLayerTree.reset( rootGroup );
286}
287
288
290{
291 if ( autoUpdate == autoUpdateModel() )
292 return;
293
294 setCustomLayerTree( autoUpdate ? nullptr : mLayout->project()->layerTreeRoot()->clone() );
296 updateFilterByMap( false );
297}
298
299void QgsLayoutItemLegend::nodeCustomPropertyChanged( QgsLayerTreeNode *, const QString &key )
300{
301 if ( key == QLatin1String( "cached_name" ) )
302 return;
303
304 if ( autoUpdateModel() )
305 {
306 // in "auto update" mode, some parameters on the main app legend may have been changed (expression filtering)
307 // we must then call updateItem to reflect the changes
308 updateFilterByMap( false );
309 }
310}
311
313{
314 return !mCustomLayerTree;
315}
316
318{
319 if ( mLegendFilterByMap == enabled )
320 return;
321
322 mLegendFilterByMap = enabled;
323 updateFilterByMap( false );
324}
325
326void QgsLayoutItemLegend::setTitle( const QString &t )
327{
328 mTitle = t;
329 mSettings.setTitle( t );
330
331 if ( mLayout && id().isEmpty() )
332 {
333 //notify the model that the display name has changed
334 mLayout->itemsModel()->updateItemDisplayName( this );
335 }
336}
338{
339 return mTitle;
340}
341
342Qt::AlignmentFlag QgsLayoutItemLegend::titleAlignment() const
343{
344 return mSettings.titleAlignment();
345}
346
347void QgsLayoutItemLegend::setTitleAlignment( Qt::AlignmentFlag alignment )
348{
349 mSettings.setTitleAlignment( alignment );
350}
351
356
358{
359 return mSettings.style( s );
360}
361
363{
364 mSettings.setStyle( s, style );
365}
366
368{
369 return mSettings.style( s ).font();
370}
371
373{
374 rstyle( s ).setFont( f );
375}
376
378{
379 rstyle( s ).setMargin( margin );
380}
381
383{
384 rstyle( s ).setMargin( side, margin );
385}
386
388{
389 return mSettings.lineSpacing();
390}
391
393{
394 mSettings.setLineSpacing( spacing );
395}
396
398{
399 return mSettings.boxSpace();
400}
401
403{
404 mSettings.setBoxSpace( s );
405}
406
408{
409 return mSettings.columnSpace();
410}
411
413{
414 mSettings.setColumnSpace( s );
415}
416
418{
419 return mSettings.fontColor();
420}
421
423{
424 mSettings.setFontColor( c );
425}
426
428{
429 return mSettings.symbolSize().width();
430}
431
433{
434 mSettings.setSymbolSize( QSizeF( w, mSettings.symbolSize().height() ) );
435}
436
438{
439 return mSettings.maximumSymbolSize();
440}
441
443{
444 mSettings.setMaximumSymbolSize( size );
445}
446
448{
449 return mSettings.minimumSymbolSize();
450}
451
453{
454 mSettings.setMinimumSymbolSize( size );
455}
456
457void QgsLayoutItemLegend::setSymbolAlignment( Qt::AlignmentFlag alignment )
458{
459 mSettings.setSymbolAlignment( alignment );
460}
461
463{
464 return mSettings.symbolAlignment();
465}
466
468{
469 return mSettings.symbolSize().height();
470}
471
473{
474 mSettings.setSymbolSize( QSizeF( mSettings.symbolSize().width(), h ) );
475}
476
478{
479 return mSettings.wmsLegendSize().width();
480}
481
483{
484 mSettings.setWmsLegendSize( QSizeF( w, mSettings.wmsLegendSize().height() ) );
485}
486
488{
489 return mSettings.wmsLegendSize().height();
490}
492{
493 mSettings.setWmsLegendSize( QSizeF( mSettings.wmsLegendSize().width(), h ) );
494}
495
497{
498 mSettings.setWrapChar( t );
499}
500
502{
503 return mSettings.wrapChar();
504}
505
507{
508 return mColumnCount;
509}
510
512{
513 mColumnCount = c;
514 mSettings.setColumnCount( c );
515}
516
518{
519 return mSettings.splitLayer();
520}
521
523{
524 mSettings.setSplitLayer( s );
525}
526
528{
529 return mSettings.equalColumnWidth();
530}
531
533{
534 mSettings.setEqualColumnWidth( s );
535}
536
538{
539 return mSettings.drawRasterStroke();
540}
541
543{
544 mSettings.setDrawRasterStroke( enabled );
545}
546
548{
549 return mSettings.rasterStrokeColor();
550}
551
553{
554 mSettings.setRasterStrokeColor( color );
555}
556
558{
559 return mSettings.rasterStrokeWidth();
560}
561
563{
564 mSettings.setRasterStrokeWidth( width );
565}
566
572
573bool QgsLayoutItemLegend::writePropertiesToElement( QDomElement &legendElem, QDomDocument &doc, const QgsReadWriteContext &context ) const
574{
575
576 //write general properties
577 legendElem.setAttribute( QStringLiteral( "title" ), mTitle );
578 legendElem.setAttribute( QStringLiteral( "titleAlignment" ), QString::number( static_cast< int >( mSettings.titleAlignment() ) ) );
579 legendElem.setAttribute( QStringLiteral( "columnCount" ), QString::number( mColumnCount ) );
580 legendElem.setAttribute( QStringLiteral( "splitLayer" ), QString::number( mSettings.splitLayer() ) );
581 legendElem.setAttribute( QStringLiteral( "equalColumnWidth" ), QString::number( mSettings.equalColumnWidth() ) );
582
583 legendElem.setAttribute( QStringLiteral( "boxSpace" ), QString::number( mSettings.boxSpace() ) );
584 legendElem.setAttribute( QStringLiteral( "columnSpace" ), QString::number( mSettings.columnSpace() ) );
585
586 legendElem.setAttribute( QStringLiteral( "symbolWidth" ), QString::number( mSettings.symbolSize().width() ) );
587 legendElem.setAttribute( QStringLiteral( "symbolHeight" ), QString::number( mSettings.symbolSize().height() ) );
588 legendElem.setAttribute( QStringLiteral( "maxSymbolSize" ), QString::number( mSettings.maximumSymbolSize() ) );
589 legendElem.setAttribute( QStringLiteral( "minSymbolSize" ), QString::number( mSettings.minimumSymbolSize() ) );
590
591 legendElem.setAttribute( QStringLiteral( "symbolAlignment" ), mSettings.symbolAlignment() );
592
593 legendElem.setAttribute( QStringLiteral( "symbolAlignment" ), mSettings.symbolAlignment() );
594 legendElem.setAttribute( QStringLiteral( "lineSpacing" ), QString::number( mSettings.lineSpacing() ) );
595
596 legendElem.setAttribute( QStringLiteral( "rasterBorder" ), mSettings.drawRasterStroke() );
597 legendElem.setAttribute( QStringLiteral( "rasterBorderColor" ), QgsSymbolLayerUtils::encodeColor( mSettings.rasterStrokeColor() ) );
598 legendElem.setAttribute( QStringLiteral( "rasterBorderWidth" ), QString::number( mSettings.rasterStrokeWidth() ) );
599
600 legendElem.setAttribute( QStringLiteral( "wmsLegendWidth" ), QString::number( mSettings.wmsLegendSize().width() ) );
601 legendElem.setAttribute( QStringLiteral( "wmsLegendHeight" ), QString::number( mSettings.wmsLegendSize().height() ) );
602 legendElem.setAttribute( QStringLiteral( "wrapChar" ), mSettings.wrapChar() );
603 legendElem.setAttribute( QStringLiteral( "fontColor" ), mSettings.fontColor().name() );
604
605 legendElem.setAttribute( QStringLiteral( "resizeToContents" ), mSizeToContents );
606
607 if ( mMap )
608 {
609 legendElem.setAttribute( QStringLiteral( "map_uuid" ), mMap->uuid() );
610 }
611
612 QDomElement legendStyles = doc.createElement( QStringLiteral( "styles" ) );
613 legendElem.appendChild( legendStyles );
614
615 style( QgsLegendStyle::Title ).writeXml( QStringLiteral( "title" ), legendStyles, doc );
616 style( QgsLegendStyle::Group ).writeXml( QStringLiteral( "group" ), legendStyles, doc );
617 style( QgsLegendStyle::Subgroup ).writeXml( QStringLiteral( "subgroup" ), legendStyles, doc );
618 style( QgsLegendStyle::Symbol ).writeXml( QStringLiteral( "symbol" ), legendStyles, doc );
619 style( QgsLegendStyle::SymbolLabel ).writeXml( QStringLiteral( "symbolLabel" ), legendStyles, doc );
620
621 if ( mCustomLayerTree )
622 {
623 // if not using auto-update - store the custom layer tree
624 mCustomLayerTree->writeXml( legendElem, context );
625 }
626
627 if ( mLegendFilterByMap )
628 {
629 legendElem.setAttribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "1" ) );
630 }
631 legendElem.setAttribute( QStringLiteral( "legendFilterByAtlas" ), mFilterOutAtlas ? QStringLiteral( "1" ) : QStringLiteral( "0" ) );
632
633 return true;
634}
635
636bool QgsLayoutItemLegend::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context )
637{
638 //read general properties
639 mTitle = itemElem.attribute( QStringLiteral( "title" ) );
640 mSettings.setTitle( mTitle );
641 if ( !itemElem.attribute( QStringLiteral( "titleAlignment" ) ).isEmpty() )
642 {
643 mSettings.setTitleAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "titleAlignment" ) ).toInt() ) );
644 }
645 int colCount = itemElem.attribute( QStringLiteral( "columnCount" ), QStringLiteral( "1" ) ).toInt();
646 if ( colCount < 1 ) colCount = 1;
647 mColumnCount = colCount;
648 mSettings.setColumnCount( mColumnCount );
649 mSettings.setSplitLayer( itemElem.attribute( QStringLiteral( "splitLayer" ), QStringLiteral( "0" ) ).toInt() == 1 );
650 mSettings.setEqualColumnWidth( itemElem.attribute( QStringLiteral( "equalColumnWidth" ), QStringLiteral( "0" ) ).toInt() == 1 );
651
652 const QDomNodeList stylesNodeList = itemElem.elementsByTagName( QStringLiteral( "styles" ) );
653 if ( !stylesNodeList.isEmpty() )
654 {
655 const QDomNode stylesNode = stylesNodeList.at( 0 );
656 for ( int i = 0; i < stylesNode.childNodes().size(); i++ )
657 {
658 const QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
660 style.readXml( styleElem, doc, context );
661 const QString name = styleElem.attribute( QStringLiteral( "name" ) );
663 if ( name == QLatin1String( "title" ) ) s = QgsLegendStyle::Title;
664 else if ( name == QLatin1String( "group" ) ) s = QgsLegendStyle::Group;
665 else if ( name == QLatin1String( "subgroup" ) ) s = QgsLegendStyle::Subgroup;
666 else if ( name == QLatin1String( "symbol" ) ) s = QgsLegendStyle::Symbol;
667 else if ( name == QLatin1String( "symbolLabel" ) ) s = QgsLegendStyle::SymbolLabel;
668 else continue;
669 setStyle( s, style );
670 }
671 }
672
673 //font color
674 QColor fontClr;
675 fontClr.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) );
676 mSettings.setFontColor( fontClr );
677
678 //spaces
679 mSettings.setBoxSpace( itemElem.attribute( QStringLiteral( "boxSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
680 mSettings.setColumnSpace( itemElem.attribute( QStringLiteral( "columnSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
681
682 mSettings.setSymbolSize( QSizeF( itemElem.attribute( QStringLiteral( "symbolWidth" ), QStringLiteral( "7.0" ) ).toDouble(), itemElem.attribute( QStringLiteral( "symbolHeight" ), QStringLiteral( "14.0" ) ).toDouble() ) );
683 mSettings.setSymbolAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "symbolAlignment" ), QString::number( Qt::AlignLeft ) ).toInt() ) );
684
685 mSettings.setMaximumSymbolSize( itemElem.attribute( QStringLiteral( "maxSymbolSize" ), QStringLiteral( "0.0" ) ).toDouble() );
686 mSettings.setMinimumSymbolSize( itemElem.attribute( QStringLiteral( "minSymbolSize" ), QStringLiteral( "0.0" ) ).toDouble() );
687
688 mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( QStringLiteral( "wmsLegendWidth" ), QStringLiteral( "50" ) ).toDouble(), itemElem.attribute( QStringLiteral( "wmsLegendHeight" ), QStringLiteral( "25" ) ).toDouble() ) );
689 mSettings.setLineSpacing( itemElem.attribute( QStringLiteral( "lineSpacing" ), QStringLiteral( "1.0" ) ).toDouble() );
690
691 mSettings.setDrawRasterStroke( itemElem.attribute( QStringLiteral( "rasterBorder" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) );
692 mSettings.setRasterStrokeColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "rasterBorderColor" ), QStringLiteral( "0,0,0" ) ) ) );
693 mSettings.setRasterStrokeWidth( itemElem.attribute( QStringLiteral( "rasterBorderWidth" ), QStringLiteral( "0" ) ).toDouble() );
694
695 mSettings.setWrapChar( itemElem.attribute( QStringLiteral( "wrapChar" ) ) );
696
697 mSizeToContents = itemElem.attribute( QStringLiteral( "resizeToContents" ), QStringLiteral( "1" ) ) != QLatin1String( "0" );
698
699 // map
700 mLegendFilterByMap = itemElem.attribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "0" ) ).toInt();
701
702 mMapUuid.clear();
703 if ( !itemElem.attribute( QStringLiteral( "map_uuid" ) ).isEmpty() )
704 {
705 mMapUuid = itemElem.attribute( QStringLiteral( "map_uuid" ) );
706 }
707 // disconnect current map
708 setupMapConnections( mMap, false );
709 mMap = nullptr;
710
711 mFilterOutAtlas = itemElem.attribute( QStringLiteral( "legendFilterByAtlas" ), QStringLiteral( "0" ) ).toInt();
712
713 // QGIS >= 2.6
714 QDomElement layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree" ) );
715 if ( layerTreeElem.isNull() )
716 layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree-group" ) );
717
718 if ( !layerTreeElem.isNull() )
719 {
720 std::unique_ptr< QgsLayerTree > tree( QgsLayerTree::readXml( layerTreeElem, context ) );
721 if ( mLayout )
722 tree->resolveReferences( mLayout->project(), true );
723 setCustomLayerTree( tree.release() );
724 }
725 else
726 setCustomLayerTree( nullptr );
727
728 return true;
729}
730
732{
733 if ( !id().isEmpty() )
734 {
735 return id();
736 }
737
738 //if no id, default to portion of title text
739 QString text = mSettings.title();
740 if ( text.isEmpty() )
741 {
742 return tr( "<Legend>" );
743 }
744 if ( text.length() > 25 )
745 {
746 return tr( "%1…" ).arg( text.left( 25 ) );
747 }
748 else
749 {
750 return text;
751 }
752}
753
754
755void QgsLayoutItemLegend::setupMapConnections( QgsLayoutItemMap *map, bool connectSlots )
756{
757 if ( !map )
758 return;
759
760 if ( !connectSlots )
761 {
762 disconnect( map, &QObject::destroyed, this, &QgsLayoutItemLegend::invalidateCurrentMap );
763 disconnect( map, &QgsLayoutObject::changed, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
764 disconnect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
765 disconnect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
766 disconnect( map, &QgsLayoutItemMap::layerStyleOverridesChanged, this, &QgsLayoutItemLegend::mapLayerStyleOverridesChanged );
767 disconnect( map, &QgsLayoutItemMap::themeChanged, this, &QgsLayoutItemLegend::mapThemeChanged );
768 }
769 else
770 {
771 connect( map, &QObject::destroyed, this, &QgsLayoutItemLegend::invalidateCurrentMap );
772 connect( map, &QgsLayoutObject::changed, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
773 connect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
774 connect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
775 connect( map, &QgsLayoutItemMap::layerStyleOverridesChanged, this, &QgsLayoutItemLegend::mapLayerStyleOverridesChanged );
776 connect( map, &QgsLayoutItemMap::themeChanged, this, &QgsLayoutItemLegend::mapThemeChanged );
777 }
778}
779
781{
782 if ( mMap == map )
783 return;
784
785 if ( mMap )
786 {
787 setupMapConnections( mMap, false );
788 }
789
790 mMap = map;
791
792 if ( mMap )
793 {
794 setupMapConnections( mMap, true );
795 mapThemeChanged( mMap->themeToRender( mMap->createExpressionContext() ) );
796 }
797
799}
800
801void QgsLayoutItemLegend::invalidateCurrentMap()
802{
803 setLinkedMap( nullptr );
804}
805
807{
809
810 bool forceUpdate = false;
811 //updates data defined properties and redraws item to match
812 if ( property == QgsLayoutObject::LegendTitle || property == QgsLayoutObject::AllProperties )
813 {
814 bool ok = false;
815 const QString t = mDataDefinedProperties.valueAsString( QgsLayoutObject::LegendTitle, context, mTitle, &ok );
816 if ( ok )
817 {
818 mSettings.setTitle( t );
819 forceUpdate = true;
820 }
821 }
823 {
824 bool ok = false;
825 const int cols = mDataDefinedProperties.valueAsInt( QgsLayoutObject::LegendColumnCount, context, mColumnCount, &ok );
826 if ( ok && cols >= 0 )
827 {
828 mSettings.setColumnCount( cols );
829 forceUpdate = true;
830 }
831 }
832 if ( forceUpdate )
833 {
835 update();
836 }
837
839}
840
841
842void QgsLayoutItemLegend::updateFilterByMapAndRedraw()
843{
844 updateFilterByMap( true );
845}
846
847void QgsLayoutItemLegend::setModelStyleOverrides( const QMap<QString, QString> &overrides )
848{
849 mLegendModel->setLayerStyleOverrides( overrides );
850 const QList< QgsLayerTreeLayer * > layers = mLegendModel->rootGroup()->findLayers();
851 for ( QgsLayerTreeLayer *nodeLayer : layers )
852 mLegendModel->refreshLayerLegend( nodeLayer );
853
854}
855
856void QgsLayoutItemLegend::clearLegendCachedData()
857{
858 std::function< void( QgsLayerTreeNode * ) > clearNodeCache;
859 clearNodeCache = [&]( QgsLayerTreeNode * node )
860 {
861 mLegendModel->clearCachedData( node );
862 if ( QgsLayerTree::isGroup( node ) )
863 {
865 const QList< QgsLayerTreeNode * > children = group->children();
866 for ( QgsLayerTreeNode *child : children )
867 {
868 clearNodeCache( child );
869 }
870 }
871 };
872
873 clearNodeCache( mLegendModel->rootGroup() );
874}
875
876void QgsLayoutItemLegend::mapLayerStyleOverridesChanged()
877{
878 if ( !mMap )
879 return;
880
881 // map's style has been changed, so make sure to update the legend here
882 if ( mLegendFilterByMap )
883 {
884 // legend is being filtered by map, so we need to re run the hit test too
885 // as the style overrides may also have affected the visible symbols
886 updateFilterByMap( false );
887 }
888 else
889 {
890 setModelStyleOverrides( mMap->layerStyleOverrides() );
891 }
892
894
895 updateFilterByMap( false );
896}
897
898void QgsLayoutItemLegend::mapThemeChanged( const QString &theme )
899{
900 if ( mThemeName == theme )
901 return;
902
903 mThemeName = theme;
904
905 // map's theme has been changed, so make sure to update the legend here
906 if ( mLegendFilterByMap )
907 {
908 // legend is being filtered by map, so we need to re run the hit test too
909 // as the style overrides may also have affected the visible symbols
910 updateFilterByMap( false );
911 }
912 else
913 {
914 if ( mThemeName.isEmpty() )
915 {
916 setModelStyleOverrides( QMap<QString, QString>() );
917 }
918 else
919 {
920 // get style overrides for theme
921 const QMap<QString, QString> overrides = mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
922 setModelStyleOverrides( overrides );
923 }
924 }
925
927
929}
930
932{
933 // ask for update
934 // the actual update will take place before the redraw.
935 // This is to avoid multiple calls to the filter
936 mFilterAskedForUpdate = true;
937
938 if ( redraw )
939 update();
940}
941
942void QgsLayoutItemLegend::doUpdateFilterByMap()
943{
944 if ( mMap )
945 {
946 if ( !mThemeName.isEmpty() )
947 {
948 // get style overrides for theme
949 const QMap<QString, QString> overrides = mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
950 mLegendModel->setLayerStyleOverrides( overrides );
951 }
952 else
953 {
954 mLegendModel->setLayerStyleOverrides( mMap->layerStyleOverrides() );
955 }
956 }
957 else
958 mLegendModel->setLayerStyleOverrides( QMap<QString, QString>() );
959
960
961 const bool filterByExpression = QgsLayerTreeUtils::hasLegendFilterExpression( *( mCustomLayerTree ? mCustomLayerTree.get() : mLayout->project()->layerTreeRoot() ) );
962
963 if ( mMap && ( mLegendFilterByMap || filterByExpression || mInAtlas ) )
964 {
965 const double dpi = mLayout->renderContext().dpi();
966
967 const QgsRectangle requestRectangle = mMap->requestedExtent();
968
969 QSizeF size( requestRectangle.width(), requestRectangle.height() );
970 size *= mLayout->convertFromLayoutUnits( mMap->mapUnitsToLayoutUnits(), QgsUnitTypes::LayoutMillimeters ).length() * dpi / 25.4;
971
972 const QgsMapSettings ms = mMap->mapSettings( requestRectangle, size, dpi, true );
973
974 QgsGeometry filterPolygon;
975 if ( mInAtlas )
976 {
977 filterPolygon = mLayout->reportContext().currentGeometry( mMap->crs() );
978 }
979 mLegendModel->setLegendFilter( &ms, /* useExtent */ mInAtlas || mLegendFilterByMap, filterPolygon, /* useExpressions */ true );
980 }
981 else
982 mLegendModel->setLegendFilterByMap( nullptr );
983
984 clearLegendCachedData();
985 mForceResize = true;
986}
987
989{
990 return mThemeName;
991}
992
994{
995 mFilterOutAtlas = doFilter;
996}
997
999{
1000 return mFilterOutAtlas;
1001}
1002
1003void QgsLayoutItemLegend::onAtlasFeature()
1004{
1005 if ( !mLayout || !mLayout->reportContext().feature().isValid() )
1006 return;
1007 mInAtlas = mFilterOutAtlas;
1009}
1010
1011void QgsLayoutItemLegend::onAtlasEnded()
1012{
1013 mInAtlas = false;
1015}
1016
1018{
1020
1021 // We only want the last scope from the map's expression context, as this contains
1022 // the map specific variables. We don't want the rest of the map's context, because that
1023 // will contain duplicate global, project, layout, etc scopes.
1024 if ( mMap )
1025 context.appendScope( mMap->createExpressionContext().popScope() );
1026
1027 QgsExpressionContextScope *scope = new QgsExpressionContextScope( tr( "Legend Settings" ) );
1028
1029 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_title" ), title(), true ) );
1030 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_column_count" ), columnCount(), true ) );
1031 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_split_layers" ), splitLayer(), true ) );
1032 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_wrap_string" ), wrapString(), true ) );
1033 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_filter_by_map" ), legendFilterByMapEnabled(), true ) );
1034 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_filter_out_atlas" ), legendFilterOutAtlas(), true ) );
1035
1036 context.appendScope( scope );
1037 return context;
1038}
1039
1044
1046{
1047 std::function<bool( QgsLayerTreeGroup *group ) >visit;
1048
1049 visit = [ =, &visit]( QgsLayerTreeGroup * group ) -> bool
1050 {
1051 const QList<QgsLayerTreeNode *> childNodes = group->children();
1052 for ( QgsLayerTreeNode *node : childNodes )
1053 {
1054 if ( QgsLayerTree::isGroup( node ) )
1055 {
1056 QgsLayerTreeGroup *nodeGroup = QgsLayerTree::toGroup( node );
1057 if ( !visit( nodeGroup ) )
1058 return false;
1059 }
1060 else if ( QgsLayerTree::isLayer( node ) )
1061 {
1062 QgsLayerTreeLayer *nodeLayer = QgsLayerTree::toLayer( node );
1063 if ( !nodeLayer->patchShape().isNull() )
1064 {
1065 QgsStyleLegendPatchShapeEntity entity( nodeLayer->patchShape() );
1066 if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity, uuid(), displayName() ) ) )
1067 return false;
1068 }
1069 const QList<QgsLayerTreeModelLegendNode *> legendNodes = mLegendModel->layerLegendNodes( nodeLayer );
1070 for ( QgsLayerTreeModelLegendNode *legendNode : legendNodes )
1071 {
1072 if ( QgsSymbolLegendNode *symbolNode = dynamic_cast< QgsSymbolLegendNode * >( legendNode ) )
1073 {
1074 if ( !symbolNode->patchShape().isNull() )
1075 {
1076 QgsStyleLegendPatchShapeEntity entity( symbolNode->patchShape() );
1077 if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity, uuid(), displayName() ) ) )
1078 return false;
1079 }
1080 }
1081 }
1082 }
1083 }
1084 return true;
1085 };
1086 return visit( mLegendModel->rootGroup( ) );
1087}
1088
1089
1090// -------------------------------------------------------------------------
1092#include "qgsvectorlayer.h"
1093#include "qgsmaplayerlegend.h"
1094
1096 : QgsLayerTreeModel( rootNode, parent )
1097 , mLayoutLegend( layout )
1098{
1101 connect( this, &QgsLegendModel::dataChanged, this, &QgsLegendModel::refreshLegend );
1102}
1103
1105 : QgsLayerTreeModel( rootNode )
1106 , mLayoutLegend( layout )
1107{
1110 connect( this, &QgsLegendModel::dataChanged, this, &QgsLegendModel::refreshLegend );
1111}
1112
1113QVariant QgsLegendModel::data( const QModelIndex &index, int role ) const
1114{
1115 // handle custom layer node labels
1116
1118 QgsLayerTreeLayer *nodeLayer = QgsLayerTree::isLayer( node ) ? QgsLayerTree::toLayer( node ) : nullptr;
1119 if ( nodeLayer && ( role == Qt::DisplayRole || role == Qt::EditRole ) )
1120 {
1121 QString name = node->customProperty( QStringLiteral( "cached_name" ) ).toString();
1122 if ( !name.isEmpty() )
1123 return name;
1124
1125 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( nodeLayer->layer() );
1126
1127 //finding the first label that is stored
1128 name = nodeLayer->customProperty( QStringLiteral( "legend/title-label" ) ).toString();
1129 if ( name.isEmpty() )
1130 name = nodeLayer->name();
1131 if ( name.isEmpty() )
1132 name = node->customProperty( QStringLiteral( "legend/title-label" ) ).toString();
1133 if ( name.isEmpty() )
1134 name = node->name();
1135 if ( nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt() )
1136 {
1137 if ( vlayer && vlayer->featureCount() >= 0 )
1138 {
1139 name += QStringLiteral( " [%1]" ).arg( vlayer->featureCount() );
1140 node->setCustomProperty( QStringLiteral( "cached_name" ), name );
1141 return name;
1142 }
1143 }
1144
1145 const bool evaluate = ( vlayer && !nodeLayer->labelExpression().isEmpty() ) || name.contains( "[%" );
1146 if ( evaluate )
1147 {
1148 QgsExpressionContext expressionContext;
1149 if ( vlayer )
1150 {
1151 connect( vlayer, &QgsVectorLayer::symbolFeatureCountMapChanged, this, &QgsLegendModel::forceRefresh, Qt::UniqueConnection );
1152 // counting is done here to ensure that a valid vector layer needs to be evaluated, count is used to validate previous count or update the count if invalidated
1153 vlayer->countSymbolFeatures();
1154 }
1155
1156 if ( mLayoutLegend )
1157 expressionContext = mLayoutLegend->createExpressionContext();
1158
1159 const QList<QgsLayerTreeModelLegendNode *> legendnodes = layerLegendNodes( nodeLayer, false );
1160 if ( legendnodes.count() > 1 ) // evaluate all existing legend nodes but leave the name for the legend evaluator
1161 {
1162 for ( QgsLayerTreeModelLegendNode *treenode : legendnodes )
1163 {
1164 if ( QgsSymbolLegendNode *symnode = qobject_cast<QgsSymbolLegendNode *>( treenode ) )
1165 symnode->evaluateLabel( expressionContext );
1166 }
1167 }
1168 else if ( QgsSymbolLegendNode *symnode = qobject_cast<QgsSymbolLegendNode *>( legendnodes.first() ) )
1169 name = symnode->evaluateLabel( expressionContext );
1170 }
1171 node->setCustomProperty( QStringLiteral( "cached_name" ), name );
1172 return name;
1173 }
1174 return QgsLayerTreeModel::data( index, role );
1175}
1176
1177Qt::ItemFlags QgsLegendModel::flags( const QModelIndex &index ) const
1178{
1179 // make the legend nodes selectable even if they are not by default
1180 if ( index2legendNode( index ) )
1181 return QgsLayerTreeModel::flags( index ) | Qt::ItemIsSelectable;
1182
1184}
1185
1186QList<QgsLayerTreeModelLegendNode *> QgsLegendModel::layerLegendNodes( QgsLayerTreeLayer *nodeLayer, bool skipNodeEmbeddedInParent ) const
1187{
1188 if ( !mLegend.contains( nodeLayer ) )
1189 return QList<QgsLayerTreeModelLegendNode *>();
1190
1191 const LayerLegendData &data = mLegend[nodeLayer];
1192 QList<QgsLayerTreeModelLegendNode *> lst( data.activeNodes );
1193 if ( !skipNodeEmbeddedInParent && data.embeddedNodeInParent )
1194 lst.prepend( data.embeddedNodeInParent );
1195 return lst;
1196}
1197
1199{
1200 node->removeCustomProperty( QStringLiteral( "cached_name" ) );
1201}
1202
1203void QgsLegendModel::forceRefresh()
1204{
1205 emit refreshLegend();
1206}
int valueAsInt(int key, const QgsExpressionContext &context, int defaultValue=0, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as an integer.
QString valueAsString(int key, const QgsExpressionContext &context, const QString &defaultString=QString(), bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a string.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
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...
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
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.
A geometry is the spatial representation of a feature.
Layer tree group node serves as a container for layers and further groups.
Layer tree node points to a map layer.
QString labelExpression() const
Returns the expression member of the LayerTreeNode.
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.
The QgsLegendRendererItem class is abstract interface for legend items returned from QgsMapLayerLegen...
The QgsLayerTreeModel class is model implementation for Qt item views framework.
Flags flags() const
Returns OR-ed combination of model flags.
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) 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)
This class is a 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 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 QgsLayerTree * readXml(QDomElement &element, const QgsReadWriteContext &context)
Load the layer tree from an XML element.
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...
void setStyleMargin(QgsLegendStyle::Style component, double margin)
Set the margin for a legend component.
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.
void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties) override
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.
QFont styleFont(QgsLegendStyle::Style component) const
Returns the font settings for a legend component.
static QgsLayoutItemLegend * create(QgsLayout *layout)
Returns a new legend item for the specified layout.
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.
QgsLegendStyle & rstyle(QgsLegendStyle::Style s)
Returns reference to modifiable legend style.
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.
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.
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.
void setStyle(QgsLegendStyle::Style component, const QgsLegendStyle &style)
Sets the style of component to style for the legend.
ExportLayerBehavior exportLayerBehavior() const override
Returns the behavior of this item during exporting to layered exports (e.g.
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 setLegendFilterByMapEnabled(bool enabled)
Set whether legend items should be filtered to show just the ones visible in the associated map.
void setSymbolHeight(double height)
Sets the legend symbol height.
void setMinimumSymbolSize(double size)
Set the minimum symbol size for symbol (in millimeters).
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.
void setRasterStrokeWidth(double width)
Sets the stroke width for the stroke drawn around raster symbol items.
double minimumSymbolSize() const
Returns the minimum symbol size (in mm).
double rasterStrokeWidth() const
Returns the stroke width (in layout units) for the stroke drawn around raster symbol items.
double lineSpacing() const
Returns the spacing in-between lines in layout units.
void invalidateCache() override
void setStyleFont(QgsLegendStyle::Style component, const QFont &font)
Sets the style font for a legend component.
QgsLegendStyle style(QgsLegendStyle::Style s) const
Returns legend style.
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.
QgsMapSettings mapSettings(const QgsRectangle &extent, QSizeF size, double dpi, bool includeLayerSettings) const
Returns map settings that will be used for drawing of the map.
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.
QgsRectangle requestedExtent() const
Calculates the extent to request and the yShift of the top-left point in case of rotation.
QMap< QString, QString > layerStyleOverrides() const
Returns stored overrides of styles for layers.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
double mapUnitsToLayoutUnits() const
Returns the conversion factor from map units to layout units.
void themeChanged(const QString &theme)
Emitted when the map's associated theme is changed.
QgsRectangle extent() const
Returns the current map extent.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
Contains settings and helpers relating to a render of a QgsLayoutItem.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
Base class for graphical items within a QgsLayout.
QgsLayoutSize sizeWithUnits() const
Returns the item's current size, including units.
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.
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.
virtual void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties)
Refreshes a data defined property for the item by reevaluating the property's value and redrawing the...
@ 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.
void refresh() override
Refreshes the item, causing a recalculation of any property overrides and recalculation of its positi...
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.
@ LegendTitle
Legend title.
@ AllProperties
All properties for item.
@ LegendColumnCount
Legend column count.
@ FlagUseAdvancedEffects
Enable advanced effects such as blend modes.
This class provides a method of storing sizes, consisting of a width and height, for use in QGIS layo...
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.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
Definition qgslayout.h:51
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...
The QgsLegendRenderer class handles automatic layout and rendering of legend.
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.
void setSymbolAlignment(Qt::AlignmentFlag alignment)
Sets the alignment for placement of legend symbols.
QString wrapChar() const
Returns the string used as a wrapping character.
void setFontColor(const QColor &c)
Sets the font color used for legend items.
void setWrapChar(const QString &t)
Sets a string to use as a wrapping character.
void setRasterStrokeColor(const QColor &color)
Sets the stroke color for the stroke drawn around raster symbol items.
void setStyle(QgsLegendStyle::Style s, const QgsLegendStyle &style)
Sets the style for a legend component.
void setColumnSpace(double s)
Sets the margin space between adjacent columns (in millimeters).
Q_DECL_DEPRECATED void setMapScale(double scale)
Sets the legend map scale.
QgsLegendStyle style(QgsLegendStyle::Style s) const
Returns the style for a legend component.
void setTitle(const QString &t)
Sets the title for the legend, which will be rendered above all legend items.
bool drawRasterStroke() const
Returns whether a stroke will be drawn around raster symbol items.
void setDrawRasterStroke(bool enabled)
Sets whether a stroke will be drawn around raster symbol items.
QSizeF wmsLegendSize() const
Returns the size (in millimeters) of WMS legend graphics shown in the legend.
double minimumSymbolSize() const
Returns the minimum symbol size (in mm).
double rasterStrokeWidth() const
Returns the stroke width (in millimeters) for the stroke drawn around raster symbol items.
void setLineSpacing(double s)
Sets the line spacing to use between lines of legend text.
void setColumnCount(int c)
Sets the desired minimum number of columns to show in the legend.
void setTitleAlignment(Qt::AlignmentFlag alignment)
Sets the alignment of the legend title.
Q_DECL_DEPRECATED void setMmPerMapUnit(double mmPerMapUnit)
Q_DECL_DEPRECATED void setDpi(int dpi)
Qt::AlignmentFlag titleAlignment() const
Returns the alignment of the legend title.
QSizeF symbolSize() const
Returns the default symbol size (in millimeters) used for legend items.
QColor fontColor() const
Returns the font color used for legend items.
double maximumSymbolSize() const
Returns the maximum symbol size (in mm).
QString title() const
Returns the title for the legend, which will be rendered above all legend items.
QColor rasterStrokeColor() const
Returns the stroke color for the stroke drawn around raster symbol items.
Q_DECL_DEPRECATED void setUseAdvancedEffects(bool use)
void setSplitLayer(bool s)
Sets whether layer components can be split over multiple columns.
double columnSpace() const
Returns the margin space between adjacent columns (in millimeters).
QgsLegendStyle & rstyle(QgsLegendStyle::Style s)
Returns modifiable reference to the style for a legend component.
void setEqualColumnWidth(bool s)
Sets whether all columns should have equal widths.
void setBoxSpace(double s)
Sets the legend box space (in millimeters), which is the empty margin around the inside of the legend...
double boxSpace() const
Returns the legend box space (in millimeters), which is the empty margin around the inside of the leg...
void setMaximumSymbolSize(double size)
Set the maximum symbol size for symbol (in millimeters).
double lineSpacing() const
Returns the line spacing to use between lines of legend text.
bool splitLayer() const
Returns true if layer components can be split over multiple columns.
void setMinimumSymbolSize(double size)
Set the minimum symbol size for symbol (in millimeters).
void setRasterStrokeWidth(double width)
Sets the stroke width for the stroke drawn around raster symbol items.
Qt::AlignmentFlag symbolAlignment() const
Returns the alignment for placement of legend symbols.
bool equalColumnWidth() const
Returns true if all columns should have equal widths.
void setSymbolSize(QSizeF s)
Sets the default symbol size (in millimeters) used for legend items.
void setWmsLegendSize(QSizeF s)
Sets the desired size (in millimeters) of WMS legend graphics shown in the legend.
Contains detailed styling information relating to how a layout legend should be rendered.
QFont font() const
Returns the font used for rendering this legend component.
void setMargin(Side side, double margin)
Sets the margin (in mm) for the specified side of the component.
Side
Margin sides.
void readXml(const QDomElement &elem, const QDomDocument &doc, const QgsReadWriteContext &context=QgsReadWriteContext())
Reads the component's style definition from an XML element.
Style
Component of legends which can be styled.
@ Group
Legend group title.
@ Symbol
Symbol icon (excluding label)
@ Subgroup
Legend subgroup title.
@ Title
Legend title.
@ SymbolLabel
Symbol label (excluding icon)
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.
The QgsMapSettings class contains configuration for rendering of the map.
double scale() const
Returns the calculated map scale.
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
double width() const
Returns the width of the rectangle.
double height() const
Returns the height of the rectangle.
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.
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.
Definition qgsstyle.h:1465
static QColor decodeColor(const QString &str)
static QString encodeColor(const QColor &color)
Implementation of legend node interface for displaying preview of vector symbols and their labels and...
@ LayoutMillimeters
Millimeters.
Represents a vector layer which manages a vector based data sets.
QgsVectorLayerFeatureCounter * countSymbolFeatures(bool storeSymbolFids=false)
Count features for symbols.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
void symbolFeatureCountMapChanged()
Emitted when the feature count for symbols on this layer has been recalculated.
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
Definition qgis.h:3061
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:3060
#define QgsDebugMsg(str)
Definition qgslogger.h:38
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.