QGIS API Documentation 3.30.0-'s-Hertogenbosch (f186b8efe0)
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 "qgslayoutmodel.h"
23#include "qgslayertree.h"
24#include "qgslayertreemodel.h"
25#include "qgslegendrenderer.h"
26#include "qgslegendstyle.h"
27#include "qgslogger.h"
28#include "qgsmapsettings.h"
29#include "qgsproject.h"
30#include "qgssymbollayerutils.h"
31#include "qgslayertreeutils.h"
32#include "qgslayoututils.h"
33#include "qgslayout.h"
36#include "qgsvectorlayer.h"
39
40#include <QDomDocument>
41#include <QDomElement>
42#include <QPainter>
44
46 : QgsLayoutItem( layout )
47 , mLegendModel( new QgsLegendModel( layout->project()->layerTreeRoot(), this ) )
48{
49#if 0 //no longer required?
50 connect( &layout->atlasComposition(), &QgsAtlasComposition::renderEnded, this, &QgsLayoutItemLegend::onAtlasEnded );
51#endif
52
53 mTitle = mSettings.title();
54
55 // Connect to the main layertreeroot.
56 // It serves in "auto update mode" as a medium between the main app legend and this one
57 connect( mLayout->project()->layerTreeRoot(), &QgsLayerTreeNode::customPropertyChanged, this, &QgsLayoutItemLegend::nodeCustomPropertyChanged );
58
59 // If project colors change, we need to redraw legend, as legend symbols may rely on project colors
60 connect( mLayout->project(), &QgsProject::projectColorsChanged, this, [ = ]
61 {
62 invalidateCache();
63 update();
64 } );
65 connect( mLegendModel.get(), &QgsLegendModel::refreshLegend, this, [ = ]
66 {
67 // NOTE -- we do NOT connect to ::refresh here, as we don't want to trigger the call to onAtlasFeature() which sets mFilterAskedForUpdate to true,
68 // causing an endless loop.
69
70 // TODO -- the call to QgsLayoutItem::refresh() is probably NOT required!
71 QgsLayoutItem::refresh();
72
73 // (this one is definitely required)
74 clearLegendCachedData();
75 } );
76}
77
79{
80 return new QgsLayoutItemLegend( layout );
81}
82
84{
86}
87
89{
90 return QgsApplication::getThemeIcon( QStringLiteral( "/mLayoutItemLegend.svg" ) );
91}
92
93QgsLayoutItem::Flags QgsLayoutItemLegend::itemFlags() const
94{
96}
97
98void QgsLayoutItemLegend::paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget )
99{
100 if ( !painter )
101 return;
102
103 if ( mFilterAskedForUpdate )
104 {
105 mFilterAskedForUpdate = false;
106 doUpdateFilterByMap();
107 }
108
109 const int dpi = painter->device()->logicalDpiX();
110 const double dotsPerMM = dpi / 25.4;
111
112 if ( mLayout )
113 {
115 // no longer required, but left set for api stability
117 mSettings.setDpi( dpi );
119 }
120 if ( mMap && mLayout )
121 {
123 // no longer required, but left set for api stability
124 mSettings.setMmPerMapUnit( mLayout->convertFromLayoutUnits( mMap->mapUnitsToLayoutUnits(), Qgis::LayoutUnit::Millimeters ).length() );
126
127 // use a temporary QgsMapSettings to find out real map scale
128 const QSizeF mapSizePixels = QSizeF( mMap->rect().width() * dotsPerMM, mMap->rect().height() * dotsPerMM );
129 const QgsRectangle mapExtent = mMap->extent();
130
131 const QgsMapSettings ms = mMap->mapSettings( mapExtent, mapSizePixels, dpi, false );
132
133 // no longer required, but left set for api stability
135 mSettings.setMapScale( ms.scale() );
137 }
138 mInitialMapScaleCalculated = true;
139
140 QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
141 legendRenderer.setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() );
142
143 const QPointF oldPos = pos();
144
145 //adjust box if width or height is too small
146 if ( mSizeToContents )
147 {
148 QgsRenderContext context = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, painter )
150
151 const QSizeF size = legendRenderer.minimumSize( &context );
152 if ( mForceResize )
153 {
154 mForceResize = false;
155
156 //set new rect, respecting position mode and data defined size/position
157 const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
158 attemptResize( newSize );
159 }
160 else if ( size.height() > rect().height() || size.width() > rect().width() )
161 {
162 //need to resize box
163 QSizeF targetSize = rect().size();
164 if ( size.height() > targetSize.height() )
165 targetSize.setHeight( size.height() );
166 if ( size.width() > targetSize.width() )
167 targetSize.setWidth( size.width() );
168
169 const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( targetSize, sizeWithUnits().units() );
170 //set new rect, respecting position mode and data defined size/position
171 attemptResize( newSize );
172 }
173 }
174
175 // attemptResize may change the legend position and would call setPos
176 // BUT the position is actually changed for the next draw, so we need to translate of the difference
177 // between oldPos and newPos
178 // the issue doesn't appear in desktop rendering but only in export because in the first one,
179 // Qt triggers a redraw on position change
180 painter->save();
181 painter->translate( pos() - oldPos );
182 QgsLayoutItem::paint( painter, itemStyle, pWidget );
183 painter->restore();
184}
185
187{
188 if ( !mMapUuid.isEmpty() )
189 {
190 setLinkedMap( qobject_cast< QgsLayoutItemMap * >( mLayout->itemByUuid( mMapUuid, true ) ) );
191 }
192}
193
195{
197 clearLegendCachedData();
198 onAtlasFeature();
199}
200
202{
203 QPainter *painter = context.renderContext().painter();
204
205 QgsRenderContext rc = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, painter, context.renderContext().scaleFactor() * 25.4 )
207
209
210 const QgsScopedQPainterState painterState( painter );
211
212 // painter is scaled to dots, so scale back to layout units
213 painter->scale( rc.scaleFactor(), rc.scaleFactor() );
214
215 painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
216
217 if ( !mSizeToContents )
218 {
219 // set a clip region to crop out parts of legend which don't fit
220 const QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() );
221 painter->setClipRect( thisPaintRect );
222 }
223
224 if ( mLayout )
225 {
226 // no longer required, but left for API compatibility
228 mSettings.setDpi( mLayout->renderContext().dpi() );
230 }
231
232
233
234
235 QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
236 legendRenderer.setLegendSize( rect().size() );
237
238 legendRenderer.drawLegend( rc );
239}
240
242{
243 if ( !mSizeToContents )
244 return;
245
246 if ( !mInitialMapScaleCalculated )
247 {
248 // this is messy - but until we have painted the item we have no knowledge of the current DPI
249 // and so cannot correctly calculate the map scale. This results in incorrect size calculations
250 // for marker symbols with size in map units, causing the legends to initially expand to huge
251 // sizes if we attempt to calculate the box size first.
252 return;
253 }
254
255 QgsRenderContext context = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, nullptr ) :
257
258 QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
259 const QSizeF size = legendRenderer.minimumSize( &context );
260 QgsDebugMsgLevel( QStringLiteral( "width = %1 height = %2" ).arg( size.width() ).arg( size.height() ), 2 );
261 if ( size.isValid() )
262 {
263 const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
264 //set new rect, respecting position mode and data defined size/position
265 attemptResize( newSize );
266 }
267}
268
270{
271 mSizeToContents = enabled;
272}
273
275{
276 return mSizeToContents;
277}
278
279void QgsLayoutItemLegend::setCustomLayerTree( QgsLayerTree *rootGroup )
280{
281 mLegendModel->setRootGroup( rootGroup ? rootGroup : ( mLayout ? mLayout->project()->layerTreeRoot() : nullptr ) );
282
283 mCustomLayerTree.reset( rootGroup );
284}
285
286
288{
289 if ( autoUpdate == autoUpdateModel() )
290 return;
291
292 setCustomLayerTree( autoUpdate ? nullptr : mLayout->project()->layerTreeRoot()->clone() );
294 updateFilterByMap( false );
295}
296
297void QgsLayoutItemLegend::nodeCustomPropertyChanged( QgsLayerTreeNode *, const QString &key )
298{
299 if ( key == QLatin1String( "cached_name" ) )
300 return;
301
302 if ( autoUpdateModel() )
303 {
304 // in "auto update" mode, some parameters on the main app legend may have been changed (expression filtering)
305 // we must then call updateItem to reflect the changes
306 updateFilterByMap( false );
307 }
308}
309
311{
312 return !mCustomLayerTree;
313}
314
316{
317 if ( mLegendFilterByMap == enabled )
318 return;
319
320 mLegendFilterByMap = enabled;
321 updateFilterByMap( false );
322}
323
324void QgsLayoutItemLegend::setTitle( const QString &t )
325{
326 mTitle = t;
327 mSettings.setTitle( t );
328
329 if ( mLayout && id().isEmpty() )
330 {
331 //notify the model that the display name has changed
332 mLayout->itemsModel()->updateItemDisplayName( this );
333 }
334}
336{
337 return mTitle;
338}
339
340Qt::AlignmentFlag QgsLayoutItemLegend::titleAlignment() const
341{
342 return mSettings.titleAlignment();
343}
344
345void QgsLayoutItemLegend::setTitleAlignment( Qt::AlignmentFlag alignment )
346{
347 mSettings.setTitleAlignment( alignment );
348}
349
351{
352 return mSettings.rstyle( s );
353}
354
356{
357 return mSettings.style( s );
358}
359
361{
362 mSettings.setStyle( s, style );
363}
364
366{
368 return mSettings.style( s ).font();
370}
371
373{
375 rstyle( s ).setFont( f );
377}
378
380{
381 rstyle( s ).setMargin( margin );
382}
383
385{
386 rstyle( s ).setMargin( side, margin );
387}
388
390{
392 return mSettings.lineSpacing();
394}
395
397{
399 mSettings.setLineSpacing( spacing );
401}
402
404{
405 return mSettings.boxSpace();
406}
407
409{
410 mSettings.setBoxSpace( s );
411}
412
414{
415 return mSettings.columnSpace();
416}
417
419{
420 mSettings.setColumnSpace( s );
421}
422
424{
426 return mSettings.fontColor();
428}
429
431{
433 mSettings.setFontColor( c );
435}
436
438{
439 return mSettings.symbolSize().width();
440}
441
443{
444 mSettings.setSymbolSize( QSizeF( w, mSettings.symbolSize().height() ) );
445}
446
448{
449 return mSettings.maximumSymbolSize();
450}
451
453{
454 mSettings.setMaximumSymbolSize( size );
455}
456
458{
459 return mSettings.minimumSymbolSize();
460}
461
463{
464 mSettings.setMinimumSymbolSize( size );
465}
466
467void QgsLayoutItemLegend::setSymbolAlignment( Qt::AlignmentFlag alignment )
468{
469 mSettings.setSymbolAlignment( alignment );
470}
471
473{
474 return mSettings.symbolAlignment();
475}
476
478{
479 return mSettings.symbolSize().height();
480}
481
483{
484 mSettings.setSymbolSize( QSizeF( mSettings.symbolSize().width(), h ) );
485}
486
488{
489 return mSettings.wmsLegendSize().width();
490}
491
493{
494 mSettings.setWmsLegendSize( QSizeF( w, mSettings.wmsLegendSize().height() ) );
495}
496
498{
499 return mSettings.wmsLegendSize().height();
500}
502{
503 mSettings.setWmsLegendSize( QSizeF( mSettings.wmsLegendSize().width(), h ) );
504}
505
507{
508 mSettings.setWrapChar( t );
509}
510
512{
513 return mSettings.wrapChar();
514}
515
517{
518 return mColumnCount;
519}
520
522{
523 mColumnCount = c;
524 mSettings.setColumnCount( c );
525}
526
528{
529 return mSettings.splitLayer();
530}
531
533{
534 mSettings.setSplitLayer( s );
535}
536
538{
539 return mSettings.equalColumnWidth();
540}
541
543{
544 mSettings.setEqualColumnWidth( s );
545}
546
548{
549 return mSettings.drawRasterStroke();
550}
551
553{
554 mSettings.setDrawRasterStroke( enabled );
555}
556
558{
559 return mSettings.rasterStrokeColor();
560}
561
563{
564 mSettings.setRasterStrokeColor( color );
565}
566
568{
569 return mSettings.rasterStrokeWidth();
570}
571
573{
574 mSettings.setRasterStrokeWidth( width );
575}
576
578{
580 updateFilterByMap( false );
581}
582
583bool QgsLayoutItemLegend::writePropertiesToElement( QDomElement &legendElem, QDomDocument &doc, const QgsReadWriteContext &context ) const
584{
585
586 //write general properties
587 legendElem.setAttribute( QStringLiteral( "title" ), mTitle );
588 legendElem.setAttribute( QStringLiteral( "titleAlignment" ), QString::number( static_cast< int >( mSettings.titleAlignment() ) ) );
589 legendElem.setAttribute( QStringLiteral( "columnCount" ), QString::number( mColumnCount ) );
590 legendElem.setAttribute( QStringLiteral( "splitLayer" ), QString::number( mSettings.splitLayer() ) );
591 legendElem.setAttribute( QStringLiteral( "equalColumnWidth" ), QString::number( mSettings.equalColumnWidth() ) );
592
593 legendElem.setAttribute( QStringLiteral( "boxSpace" ), QString::number( mSettings.boxSpace() ) );
594 legendElem.setAttribute( QStringLiteral( "columnSpace" ), QString::number( mSettings.columnSpace() ) );
595
596 legendElem.setAttribute( QStringLiteral( "symbolWidth" ), QString::number( mSettings.symbolSize().width() ) );
597 legendElem.setAttribute( QStringLiteral( "symbolHeight" ), QString::number( mSettings.symbolSize().height() ) );
598 legendElem.setAttribute( QStringLiteral( "maxSymbolSize" ), QString::number( mSettings.maximumSymbolSize() ) );
599 legendElem.setAttribute( QStringLiteral( "minSymbolSize" ), QString::number( mSettings.minimumSymbolSize() ) );
600
601 legendElem.setAttribute( QStringLiteral( "symbolAlignment" ), mSettings.symbolAlignment() );
602
603 legendElem.setAttribute( QStringLiteral( "symbolAlignment" ), mSettings.symbolAlignment() );
604
605 legendElem.setAttribute( QStringLiteral( "rasterBorder" ), mSettings.drawRasterStroke() );
606 legendElem.setAttribute( QStringLiteral( "rasterBorderColor" ), QgsSymbolLayerUtils::encodeColor( mSettings.rasterStrokeColor() ) );
607 legendElem.setAttribute( QStringLiteral( "rasterBorderWidth" ), QString::number( mSettings.rasterStrokeWidth() ) );
608
609 legendElem.setAttribute( QStringLiteral( "wmsLegendWidth" ), QString::number( mSettings.wmsLegendSize().width() ) );
610 legendElem.setAttribute( QStringLiteral( "wmsLegendHeight" ), QString::number( mSettings.wmsLegendSize().height() ) );
611 legendElem.setAttribute( QStringLiteral( "wrapChar" ), mSettings.wrapChar() );
612
613 legendElem.setAttribute( QStringLiteral( "resizeToContents" ), mSizeToContents );
614
615 if ( mMap )
616 {
617 legendElem.setAttribute( QStringLiteral( "map_uuid" ), mMap->uuid() );
618 }
619
620 QDomElement legendStyles = doc.createElement( QStringLiteral( "styles" ) );
621 legendElem.appendChild( legendStyles );
622
623 style( QgsLegendStyle::Title ).writeXml( QStringLiteral( "title" ), legendStyles, doc, context );
624 style( QgsLegendStyle::Group ).writeXml( QStringLiteral( "group" ), legendStyles, doc, context );
625 style( QgsLegendStyle::Subgroup ).writeXml( QStringLiteral( "subgroup" ), legendStyles, doc, context );
626 style( QgsLegendStyle::Symbol ).writeXml( QStringLiteral( "symbol" ), legendStyles, doc, context );
627 style( QgsLegendStyle::SymbolLabel ).writeXml( QStringLiteral( "symbolLabel" ), legendStyles, doc, context );
628
629 if ( mCustomLayerTree )
630 {
631 // if not using auto-update - store the custom layer tree
632 mCustomLayerTree->writeXml( legendElem, context );
633 }
634
635 if ( mLegendFilterByMap )
636 {
637 legendElem.setAttribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "1" ) );
638 }
639 legendElem.setAttribute( QStringLiteral( "legendFilterByAtlas" ), mFilterOutAtlas ? QStringLiteral( "1" ) : QStringLiteral( "0" ) );
640
641 return true;
642}
643
644bool QgsLayoutItemLegend::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context )
645{
646 //read general properties
647 mTitle = itemElem.attribute( QStringLiteral( "title" ) );
648 mSettings.setTitle( mTitle );
649 if ( !itemElem.attribute( QStringLiteral( "titleAlignment" ) ).isEmpty() )
650 {
651 mSettings.setTitleAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "titleAlignment" ) ).toInt() ) );
652 }
653 int colCount = itemElem.attribute( QStringLiteral( "columnCount" ), QStringLiteral( "1" ) ).toInt();
654 if ( colCount < 1 ) colCount = 1;
655 mColumnCount = colCount;
656 mSettings.setColumnCount( mColumnCount );
657 mSettings.setSplitLayer( itemElem.attribute( QStringLiteral( "splitLayer" ), QStringLiteral( "0" ) ).toInt() == 1 );
658 mSettings.setEqualColumnWidth( itemElem.attribute( QStringLiteral( "equalColumnWidth" ), QStringLiteral( "0" ) ).toInt() == 1 );
659
660 const QDomNodeList stylesNodeList = itemElem.elementsByTagName( QStringLiteral( "styles" ) );
661 if ( !stylesNodeList.isEmpty() )
662 {
663 const QDomNode stylesNode = stylesNodeList.at( 0 );
664 for ( int i = 0; i < stylesNode.childNodes().size(); i++ )
665 {
666 const QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
668 style.readXml( styleElem, doc, context );
669 const QString name = styleElem.attribute( QStringLiteral( "name" ) );
671 if ( name == QLatin1String( "title" ) ) s = QgsLegendStyle::Title;
672 else if ( name == QLatin1String( "group" ) ) s = QgsLegendStyle::Group;
673 else if ( name == QLatin1String( "subgroup" ) ) s = QgsLegendStyle::Subgroup;
674 else if ( name == QLatin1String( "symbol" ) ) s = QgsLegendStyle::Symbol;
675 else if ( name == QLatin1String( "symbolLabel" ) ) s = QgsLegendStyle::SymbolLabel;
676 else continue;
677 setStyle( s, style );
678 }
679 }
680
681 //font color
682 if ( itemElem.hasAttribute( QStringLiteral( "fontColor" ) ) )
683 {
684 QColor fontClr;
685 fontClr.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) );
690 }
691
692 //spaces
693 mSettings.setBoxSpace( itemElem.attribute( QStringLiteral( "boxSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
694 mSettings.setColumnSpace( itemElem.attribute( QStringLiteral( "columnSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
695
696 mSettings.setSymbolSize( QSizeF( itemElem.attribute( QStringLiteral( "symbolWidth" ), QStringLiteral( "7.0" ) ).toDouble(), itemElem.attribute( QStringLiteral( "symbolHeight" ), QStringLiteral( "14.0" ) ).toDouble() ) );
697 mSettings.setSymbolAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "symbolAlignment" ), QString::number( Qt::AlignLeft ) ).toInt() ) );
698
699 mSettings.setMaximumSymbolSize( itemElem.attribute( QStringLiteral( "maxSymbolSize" ), QStringLiteral( "0.0" ) ).toDouble() );
700 mSettings.setMinimumSymbolSize( itemElem.attribute( QStringLiteral( "minSymbolSize" ), QStringLiteral( "0.0" ) ).toDouble() );
701
702 mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( QStringLiteral( "wmsLegendWidth" ), QStringLiteral( "50" ) ).toDouble(), itemElem.attribute( QStringLiteral( "wmsLegendHeight" ), QStringLiteral( "25" ) ).toDouble() ) );
703
704 if ( itemElem.hasAttribute( QStringLiteral( "lineSpacing" ) ) )
705 {
706 const double spacing = itemElem.attribute( QStringLiteral( "lineSpacing" ), QStringLiteral( "1.0" ) ).toDouble();
707 // line spacing *was* a fixed amount (in mm) added between each line of text.
709 // assume font sizes in points, since that was what we always had from before this method was deprecated
710 f.setLineHeight( f.size() * 0.352778 + spacing );
711 f.setLineHeightUnit( Qgis::RenderUnit::Millimeters );
713
715 f.setLineHeight( f.size() * 0.352778 + spacing );
716 f.setLineHeightUnit( Qgis::RenderUnit::Millimeters );
718
720 f.setLineHeight( f.size() * 0.352778 + spacing );
721 f.setLineHeightUnit( Qgis::RenderUnit::Millimeters );
723
725 f.setLineHeight( f.size() * 0.352778 + spacing );
726 f.setLineHeightUnit( Qgis::RenderUnit::Millimeters );
728 }
729
730 mSettings.setDrawRasterStroke( itemElem.attribute( QStringLiteral( "rasterBorder" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) );
731 mSettings.setRasterStrokeColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "rasterBorderColor" ), QStringLiteral( "0,0,0" ) ) ) );
732 mSettings.setRasterStrokeWidth( itemElem.attribute( QStringLiteral( "rasterBorderWidth" ), QStringLiteral( "0" ) ).toDouble() );
733
734 mSettings.setWrapChar( itemElem.attribute( QStringLiteral( "wrapChar" ) ) );
735
736 mSizeToContents = itemElem.attribute( QStringLiteral( "resizeToContents" ), QStringLiteral( "1" ) ) != QLatin1String( "0" );
737
738 // map
739 mLegendFilterByMap = itemElem.attribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "0" ) ).toInt();
740
741 mMapUuid.clear();
742 if ( !itemElem.attribute( QStringLiteral( "map_uuid" ) ).isEmpty() )
743 {
744 mMapUuid = itemElem.attribute( QStringLiteral( "map_uuid" ) );
745 }
746 // disconnect current map
747 setupMapConnections( mMap, false );
748 mMap = nullptr;
749
750 mFilterOutAtlas = itemElem.attribute( QStringLiteral( "legendFilterByAtlas" ), QStringLiteral( "0" ) ).toInt();
751
752 // QGIS >= 2.6
753 QDomElement layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree" ) );
754 if ( layerTreeElem.isNull() )
755 layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree-group" ) );
756
757 if ( !layerTreeElem.isNull() )
758 {
759 std::unique_ptr< QgsLayerTree > tree( QgsLayerTree::readXml( layerTreeElem, context ) );
760 if ( mLayout )
761 tree->resolveReferences( mLayout->project(), true );
762 setCustomLayerTree( tree.release() );
763 }
764 else
765 setCustomLayerTree( nullptr );
766
767 return true;
768}
769
771{
772 if ( !id().isEmpty() )
773 {
774 return id();
775 }
776
777 //if no id, default to portion of title text
778 QString text = mSettings.title();
779 if ( text.isEmpty() )
780 {
781 return tr( "<Legend>" );
782 }
783 if ( text.length() > 25 )
784 {
785 return tr( "%1…" ).arg( text.left( 25 ) );
786 }
787 else
788 {
789 return text;
790 }
791}
792
793
794void QgsLayoutItemLegend::setupMapConnections( QgsLayoutItemMap *map, bool connectSlots )
795{
796 if ( !map )
797 return;
798
799 if ( !connectSlots )
800 {
801 disconnect( map, &QObject::destroyed, this, &QgsLayoutItemLegend::invalidateCurrentMap );
802 disconnect( map, &QgsLayoutObject::changed, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
803 disconnect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
804 disconnect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
805 disconnect( map, &QgsLayoutItemMap::layerStyleOverridesChanged, this, &QgsLayoutItemLegend::mapLayerStyleOverridesChanged );
806 disconnect( map, &QgsLayoutItemMap::themeChanged, this, &QgsLayoutItemLegend::mapThemeChanged );
807 }
808 else
809 {
810 connect( map, &QObject::destroyed, this, &QgsLayoutItemLegend::invalidateCurrentMap );
811 connect( map, &QgsLayoutObject::changed, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
812 connect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
813 connect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
814 connect( map, &QgsLayoutItemMap::layerStyleOverridesChanged, this, &QgsLayoutItemLegend::mapLayerStyleOverridesChanged );
815 connect( map, &QgsLayoutItemMap::themeChanged, this, &QgsLayoutItemLegend::mapThemeChanged );
816 }
817}
818
820{
821 if ( mMap == map )
822 return;
823
824 if ( mMap )
825 {
826 setupMapConnections( mMap, false );
827 }
828
829 mMap = map;
830
831 if ( mMap )
832 {
833 setupMapConnections( mMap, true );
834 mapThemeChanged( mMap->themeToRender( mMap->createExpressionContext() ) );
835 }
836
838}
839
840void QgsLayoutItemLegend::invalidateCurrentMap()
841{
842 setLinkedMap( nullptr );
843}
844
846{
848
849 bool forceUpdate = false;
850 //updates data defined properties and redraws item to match
851 if ( property == QgsLayoutObject::LegendTitle || property == QgsLayoutObject::AllProperties )
852 {
853 bool ok = false;
854 const QString t = mDataDefinedProperties.valueAsString( QgsLayoutObject::LegendTitle, context, mTitle, &ok );
855 if ( ok )
856 {
857 mSettings.setTitle( t );
858 forceUpdate = true;
859 }
860 }
862 {
863 bool ok = false;
864 const int cols = mDataDefinedProperties.valueAsInt( QgsLayoutObject::LegendColumnCount, context, mColumnCount, &ok );
865 if ( ok && cols >= 0 )
866 {
867 mSettings.setColumnCount( cols );
868 forceUpdate = true;
869 }
870 }
871 if ( forceUpdate )
872 {
874 update();
875 }
876
878}
879
880
881void QgsLayoutItemLegend::updateFilterByMapAndRedraw()
882{
883 updateFilterByMap( true );
884}
885
886void QgsLayoutItemLegend::setModelStyleOverrides( const QMap<QString, QString> &overrides )
887{
888 mLegendModel->setLayerStyleOverrides( overrides );
889 const QList< QgsLayerTreeLayer * > layers = mLegendModel->rootGroup()->findLayers();
890 for ( QgsLayerTreeLayer *nodeLayer : layers )
891 mLegendModel->refreshLayerLegend( nodeLayer );
892
893}
894
895void QgsLayoutItemLegend::clearLegendCachedData()
896{
897 std::function< void( QgsLayerTreeNode * ) > clearNodeCache;
898 clearNodeCache = [&]( QgsLayerTreeNode * node )
899 {
900 mLegendModel->clearCachedData( node );
901 if ( QgsLayerTree::isGroup( node ) )
902 {
904 const QList< QgsLayerTreeNode * > children = group->children();
905 for ( QgsLayerTreeNode *child : children )
906 {
907 clearNodeCache( child );
908 }
909 }
910 };
911
912 clearNodeCache( mLegendModel->rootGroup() );
913}
914
915void QgsLayoutItemLegend::mapLayerStyleOverridesChanged()
916{
917 if ( !mMap )
918 return;
919
920 // map's style has been changed, so make sure to update the legend here
921 if ( mLegendFilterByMap )
922 {
923 // legend is being filtered by map, so we need to re run the hit test too
924 // as the style overrides may also have affected the visible symbols
925 updateFilterByMap( false );
926 }
927 else
928 {
929 setModelStyleOverrides( mMap->layerStyleOverrides() );
930 }
931
933
934 updateFilterByMap( false );
935}
936
937void QgsLayoutItemLegend::mapThemeChanged( const QString &theme )
938{
939 if ( mThemeName == theme )
940 return;
941
942 mThemeName = theme;
943
944 // map's theme has been changed, so make sure to update the legend here
945 if ( mLegendFilterByMap )
946 {
947 // legend is being filtered by map, so we need to re run the hit test too
948 // as the style overrides may also have affected the visible symbols
949 updateFilterByMap( false );
950 }
951 else
952 {
953 if ( mThemeName.isEmpty() )
954 {
955 setModelStyleOverrides( QMap<QString, QString>() );
956 }
957 else
958 {
959 // get style overrides for theme
960 const QMap<QString, QString> overrides = mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
961 setModelStyleOverrides( overrides );
962 }
963 }
964
966
968}
969
971{
972 // ask for update
973 // the actual update will take place before the redraw.
974 // This is to avoid multiple calls to the filter
975 mFilterAskedForUpdate = true;
976
977 if ( redraw )
978 update();
979}
980
981void QgsLayoutItemLegend::doUpdateFilterByMap()
982{
983 if ( mMap )
984 {
985 if ( !mThemeName.isEmpty() )
986 {
987 // get style overrides for theme
988 const QMap<QString, QString> overrides = mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
989 mLegendModel->setLayerStyleOverrides( overrides );
990 }
991 else
992 {
993 mLegendModel->setLayerStyleOverrides( mMap->layerStyleOverrides() );
994 }
995 }
996 else
997 mLegendModel->setLayerStyleOverrides( QMap<QString, QString>() );
998
999
1000 const bool filterByExpression = QgsLayerTreeUtils::hasLegendFilterExpression( *( mCustomLayerTree ? mCustomLayerTree.get() : mLayout->project()->layerTreeRoot() ) );
1001
1002 if ( mMap && ( mLegendFilterByMap || filterByExpression || mInAtlas ) )
1003 {
1004 const double dpi = mLayout->renderContext().dpi();
1005
1006 const QgsRectangle requestRectangle = mMap->requestedExtent();
1007
1008 QSizeF size( requestRectangle.width(), requestRectangle.height() );
1009 size *= mLayout->convertFromLayoutUnits( mMap->mapUnitsToLayoutUnits(), Qgis::LayoutUnit::Millimeters ).length() * dpi / 25.4;
1010
1011 const QgsMapSettings ms = mMap->mapSettings( requestRectangle, size, dpi, true );
1012
1013 QgsGeometry filterPolygon;
1014 if ( mInAtlas )
1015 {
1016 filterPolygon = mLayout->reportContext().currentGeometry( mMap->crs() );
1017 }
1018 mLegendModel->setLegendFilter( &ms, /* useExtent */ mInAtlas || mLegendFilterByMap, filterPolygon, /* useExpressions */ true );
1019 }
1020 else
1021 mLegendModel->setLegendFilterByMap( nullptr );
1022
1023 clearLegendCachedData();
1024 mForceResize = true;
1025}
1026
1028{
1029 return mThemeName;
1030}
1031
1033{
1034 mFilterOutAtlas = doFilter;
1035}
1036
1038{
1039 return mFilterOutAtlas;
1040}
1041
1042void QgsLayoutItemLegend::onAtlasFeature()
1043{
1044 if ( !mLayout || !mLayout->reportContext().feature().isValid() )
1045 return;
1046 mInAtlas = mFilterOutAtlas;
1048}
1049
1050void QgsLayoutItemLegend::onAtlasEnded()
1051{
1052 mInAtlas = false;
1054}
1055
1057{
1059
1060 // We only want the last scope from the map's expression context, as this contains
1061 // the map specific variables. We don't want the rest of the map's context, because that
1062 // will contain duplicate global, project, layout, etc scopes.
1063 if ( mMap )
1064 context.appendScope( mMap->createExpressionContext().popScope() );
1065
1066 QgsExpressionContextScope *scope = new QgsExpressionContextScope( tr( "Legend Settings" ) );
1067
1068 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_title" ), title(), true ) );
1069 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_column_count" ), columnCount(), true ) );
1070 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_split_layers" ), splitLayer(), true ) );
1071 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_wrap_string" ), wrapString(), true ) );
1072 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_filter_by_map" ), legendFilterByMapEnabled(), true ) );
1073 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_filter_out_atlas" ), legendFilterOutAtlas(), true ) );
1074
1075 context.appendScope( scope );
1076 return context;
1077}
1078
1080{
1081 return MustPlaceInOwnLayer;
1082}
1083
1085{
1086 std::function<bool( QgsLayerTreeGroup *group ) >visit;
1087
1088 visit = [ =, &visit]( QgsLayerTreeGroup * group ) -> bool
1089 {
1090 const QList<QgsLayerTreeNode *> childNodes = group->children();
1091 for ( QgsLayerTreeNode *node : childNodes )
1092 {
1093 if ( QgsLayerTree::isGroup( node ) )
1094 {
1095 QgsLayerTreeGroup *nodeGroup = QgsLayerTree::toGroup( node );
1096 if ( !visit( nodeGroup ) )
1097 return false;
1098 }
1099 else if ( QgsLayerTree::isLayer( node ) )
1100 {
1101 QgsLayerTreeLayer *nodeLayer = QgsLayerTree::toLayer( node );
1102 if ( !nodeLayer->patchShape().isNull() )
1103 {
1104 QgsStyleLegendPatchShapeEntity entity( nodeLayer->patchShape() );
1105 if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity, uuid(), displayName() ) ) )
1106 return false;
1107 }
1108 const QList<QgsLayerTreeModelLegendNode *> legendNodes = mLegendModel->layerLegendNodes( nodeLayer );
1109 for ( QgsLayerTreeModelLegendNode *legendNode : legendNodes )
1110 {
1111 if ( QgsSymbolLegendNode *symbolNode = dynamic_cast< QgsSymbolLegendNode * >( legendNode ) )
1112 {
1113 if ( !symbolNode->patchShape().isNull() )
1114 {
1115 QgsStyleLegendPatchShapeEntity entity( symbolNode->patchShape() );
1116 if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity, uuid(), displayName() ) ) )
1117 return false;
1118 }
1119 }
1120 }
1121 }
1122 }
1123 return true;
1124 };
1125 return visit( mLegendModel->rootGroup( ) );
1126}
1127
1128
1129// -------------------------------------------------------------------------
1130
1132 : QgsLayerTreeModel( rootNode, parent )
1133 , mLayoutLegend( layout )
1134{
1137 connect( this, &QgsLegendModel::dataChanged, this, &QgsLegendModel::refreshLegend );
1138}
1139
1141 : QgsLayerTreeModel( rootNode )
1142 , mLayoutLegend( layout )
1143{
1146 connect( this, &QgsLegendModel::dataChanged, this, &QgsLegendModel::refreshLegend );
1147}
1148
1149QVariant QgsLegendModel::data( const QModelIndex &index, int role ) const
1150{
1151 // handle custom layer node labels
1152
1154 QgsLayerTreeLayer *nodeLayer = QgsLayerTree::isLayer( node ) ? QgsLayerTree::toLayer( node ) : nullptr;
1155 if ( nodeLayer && ( role == Qt::DisplayRole || role == Qt::EditRole ) )
1156 {
1157 QString name = node->customProperty( QStringLiteral( "cached_name" ) ).toString();
1158 if ( !name.isEmpty() )
1159 return name;
1160
1161 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( nodeLayer->layer() );
1162
1163 //finding the first label that is stored
1164 name = nodeLayer->customProperty( QStringLiteral( "legend/title-label" ) ).toString();
1165 if ( name.isEmpty() )
1166 name = nodeLayer->name();
1167 if ( name.isEmpty() )
1168 name = node->customProperty( QStringLiteral( "legend/title-label" ) ).toString();
1169 if ( name.isEmpty() )
1170 name = node->name();
1171 if ( nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt() )
1172 {
1173 if ( vlayer && vlayer->featureCount() >= 0 )
1174 {
1175 name += QStringLiteral( " [%1]" ).arg( vlayer->featureCount() );
1176 node->setCustomProperty( QStringLiteral( "cached_name" ), name );
1177 return name;
1178 }
1179 }
1180
1181 const bool evaluate = ( vlayer && !nodeLayer->labelExpression().isEmpty() ) || name.contains( "[%" );
1182 if ( evaluate )
1183 {
1184 QgsExpressionContext expressionContext;
1185 if ( vlayer )
1186 {
1187 connect( vlayer, &QgsVectorLayer::symbolFeatureCountMapChanged, this, &QgsLegendModel::forceRefresh, Qt::UniqueConnection );
1188 // 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
1189 vlayer->countSymbolFeatures();
1190 }
1191
1192 if ( mLayoutLegend )
1193 expressionContext = mLayoutLegend->createExpressionContext();
1194
1195 const QList<QgsLayerTreeModelLegendNode *> legendnodes = layerLegendNodes( nodeLayer, false );
1196 if ( legendnodes.count() > 1 ) // evaluate all existing legend nodes but leave the name for the legend evaluator
1197 {
1198 for ( QgsLayerTreeModelLegendNode *treenode : legendnodes )
1199 {
1200 if ( QgsSymbolLegendNode *symnode = qobject_cast<QgsSymbolLegendNode *>( treenode ) )
1201 symnode->evaluateLabel( expressionContext );
1202 }
1203 }
1204 else if ( QgsSymbolLegendNode *symnode = qobject_cast<QgsSymbolLegendNode *>( legendnodes.first() ) )
1205 name = symnode->evaluateLabel( expressionContext );
1206 }
1207 node->setCustomProperty( QStringLiteral( "cached_name" ), name );
1208 return name;
1209 }
1210 return QgsLayerTreeModel::data( index, role );
1211}
1212
1213Qt::ItemFlags QgsLegendModel::flags( const QModelIndex &index ) const
1214{
1215 // make the legend nodes selectable even if they are not by default
1216 if ( index2legendNode( index ) )
1217 return QgsLayerTreeModel::flags( index ) | Qt::ItemIsSelectable;
1218
1220}
1221
1222QList<QgsLayerTreeModelLegendNode *> QgsLegendModel::layerLegendNodes( QgsLayerTreeLayer *nodeLayer, bool skipNodeEmbeddedInParent ) const
1223{
1224 if ( !mLegend.contains( nodeLayer ) )
1225 return QList<QgsLayerTreeModelLegendNode *>();
1226
1227 const LayerLegendData &data = mLegend[nodeLayer];
1228 QList<QgsLayerTreeModelLegendNode *> lst( data.activeNodes );
1229 if ( !skipNodeEmbeddedInParent && data.embeddedNodeInParent )
1230 lst.prepend( data.embeddedNodeInParent );
1231 return lst;
1232}
1233
1235{
1236 node->removeCustomProperty( QStringLiteral( "cached_name" ) );
1237}
1238
1239void QgsLegendModel::forceRefresh()
1240{
1241 emit refreshLegend();
1242}
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.
Definition: qgsgeometry.h:164
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.
Definition: qgslayertree.h:33
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
Definition: qgslayertree.h:75
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
Definition: qgslayertree.h:53
static bool isGroup(QgsLayerTreeNode *node)
Check whether the node is a valid group node.
Definition: qgslayertree.h:43
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.
Definition: qgslayertree.h:64
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.
Q_DECL_DEPRECATED 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.
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.
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.
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 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.
Q_DECL_DEPRECATED double lineSpacing() const
Returns the spacing in-between lines in layout units.
Q_DECL_DEPRECATED 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.
Definition: qgslayoutitem.h:44
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
Definition: qgslayoutitem.h:71
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 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...
Definition: qgslayoutsize.h:41
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:50
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.
Q_DECL_DEPRECATED 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.
Q_DECL_DEPRECATED 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.
Q_DECL_DEPRECATED 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 double lineSpacing() const
Returns the line spacing to use between lines of legend text.
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).
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.
Q_DECL_DEPRECATED QFont font() const
Returns the font used for rendering this legend component.
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.
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)
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.
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.
Definition: qgsrectangle.h:42
double height() const SIP_HOLDGIL
Returns the height of the rectangle.
Definition: qgsrectangle.h:230
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
Definition: qgsrectangle.h:223
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:1464
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...
Container for all settings relating to text rendering.
Definition: qgstextformat.h:41
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 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.
QgsLayerTreeModelLegendNode * legendNode(const QString &rule, QgsLayerTreeModel &model)
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:4093
#define Q_NOWARN_DEPRECATED_PUSH
Definition: qgis.h:4092
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
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.