QGIS API Documentation  3.24.2-Tisler (13c1a02865)
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"
20 #include "qgslayoutitemregistry.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"
34 #include "qgsmapthemecollection.h"
35 #include "qgsstyleentityvisitor.h"
36 #include <QDomDocument>
37 #include <QDomElement>
38 #include <QPainter>
39 #include "qgsexpressioncontext.h"
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, &QgsLayoutItemLegend::refresh );
62 }
63 
65 {
66  return new QgsLayoutItemLegend( layout );
67 }
68 
70 {
72 }
73 
75 {
76  return QgsApplication::getThemeIcon( QStringLiteral( "/mLayoutItemLegend.svg" ) );
77 }
78 
79 QgsLayoutItem::Flags QgsLayoutItemLegend::itemFlags() const
80 {
82 }
83 
84 void QgsLayoutItemLegend::paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget )
85 {
86  if ( !painter )
87  return;
88 
89  if ( mFilterAskedForUpdate )
90  {
91  mFilterAskedForUpdate = false;
92  doUpdateFilterByMap();
93  }
94 
95  const int dpi = painter->device()->logicalDpiX();
96  const double dotsPerMM = dpi / 25.4;
97 
98  if ( mLayout )
99  {
101  // no longer required, but left set for api stability
102  mSettings.setUseAdvancedEffects( mLayout->renderContext().flags() & QgsLayoutRenderContext::FlagUseAdvancedEffects );
103  mSettings.setDpi( dpi );
105  }
106  if ( mMap && mLayout )
107  {
109  // no longer required, but left set for api stability
110  mSettings.setMmPerMapUnit( mLayout->convertFromLayoutUnits( mMap->mapUnitsToLayoutUnits(), QgsUnitTypes::LayoutMillimeters ).length() );
112 
113  // use a temporary QgsMapSettings to find out real map scale
114  const QSizeF mapSizePixels = QSizeF( mMap->rect().width() * dotsPerMM, mMap->rect().height() * dotsPerMM );
115  const QgsRectangle mapExtent = mMap->extent();
116 
117  const QgsMapSettings ms = mMap->mapSettings( mapExtent, mapSizePixels, dpi, false );
118 
119  // no longer required, but left set for api stability
121  mSettings.setMapScale( ms.scale() );
123  }
124  mInitialMapScaleCalculated = true;
125 
126  QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
127  legendRenderer.setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() );
128 
129  //adjust box if width or height is too small
130  if ( mSizeToContents )
131  {
132  QgsRenderContext context = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, painter )
134 
135  const QSizeF size = legendRenderer.minimumSize( &context );
136  if ( mForceResize )
137  {
138  mForceResize = false;
139 
140  //set new rect, respecting position mode and data defined size/position
141  const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
142  attemptResize( newSize );
143  }
144  else if ( size.height() > rect().height() || size.width() > rect().width() )
145  {
146  //need to resize box
147  QSizeF targetSize = rect().size();
148  if ( size.height() > targetSize.height() )
149  targetSize.setHeight( size.height() );
150  if ( size.width() > targetSize.width() )
151  targetSize.setWidth( size.width() );
152 
153  const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( targetSize, sizeWithUnits().units() );
154  //set new rect, respecting position mode and data defined size/position
155  attemptResize( newSize );
156  }
157  }
158 
159  QgsLayoutItem::paint( painter, itemStyle, pWidget );
160 }
161 
163 {
164  if ( !mMapUuid.isEmpty() )
165  {
166  setLinkedMap( qobject_cast< QgsLayoutItemMap * >( mLayout->itemByUuid( mMapUuid, true ) ) );
167  }
168 }
169 
171 {
173  clearLegendCachedData();
174  onAtlasFeature();
175 }
176 
178 {
179  QPainter *painter = context.renderContext().painter();
180 
181  QgsRenderContext rc = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, painter, context.renderContext().scaleFactor() * 25.4 )
183 
185 
186  const QgsScopedQPainterState painterState( painter );
187 
188  // painter is scaled to dots, so scale back to layout units
189  painter->scale( rc.scaleFactor(), rc.scaleFactor() );
190 
191  painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
192 
193  if ( !mSizeToContents )
194  {
195  // set a clip region to crop out parts of legend which don't fit
196  const QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() );
197  painter->setClipRect( thisPaintRect );
198  }
199 
200  if ( mLayout )
201  {
202  // no longer required, but left for API compatibility
204  mSettings.setDpi( mLayout->renderContext().dpi() );
206  }
207 
208 
209 
210 
211  QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
212  legendRenderer.setLegendSize( rect().size() );
213 
214  legendRenderer.drawLegend( rc );
215 }
216 
218 {
219  if ( !mSizeToContents )
220  return;
221 
222  if ( !mInitialMapScaleCalculated )
223  {
224  // this is messy - but until we have painted the item we have no knowledge of the current DPI
225  // and so cannot correctly calculate the map scale. This results in incorrect size calculations
226  // for marker symbols with size in map units, causing the legends to initially expand to huge
227  // sizes if we attempt to calculate the box size first.
228  return;
229  }
230 
231  QgsRenderContext context = mMap ? QgsLayoutUtils::createRenderContextForMap( mMap, nullptr ) :
233 
234  QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
235  const QSizeF size = legendRenderer.minimumSize( &context );
236  QgsDebugMsg( QStringLiteral( "width = %1 height = %2" ).arg( size.width() ).arg( size.height() ) );
237  if ( size.isValid() )
238  {
239  const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
240  //set new rect, respecting position mode and data defined size/position
241  attemptResize( newSize );
242  }
243 }
244 
246 {
247  mSizeToContents = enabled;
248 }
249 
251 {
252  return mSizeToContents;
253 }
254 
255 void QgsLayoutItemLegend::setCustomLayerTree( QgsLayerTree *rootGroup )
256 {
257  mLegendModel->setRootGroup( rootGroup ? rootGroup : ( mLayout ? mLayout->project()->layerTreeRoot() : nullptr ) );
258 
259  mCustomLayerTree.reset( rootGroup );
260 }
261 
262 
264 {
265  if ( autoUpdate == autoUpdateModel() )
266  return;
267 
268  setCustomLayerTree( autoUpdate ? nullptr : mLayout->project()->layerTreeRoot()->clone() );
269  adjustBoxSize();
270  updateFilterByMap( false );
271 }
272 
273 void QgsLayoutItemLegend::nodeCustomPropertyChanged( QgsLayerTreeNode *, const QString &key )
274 {
275  if ( key == QLatin1String( "cached_name" ) )
276  return;
277 
278  if ( autoUpdateModel() )
279  {
280  // in "auto update" mode, some parameters on the main app legend may have been changed (expression filtering)
281  // we must then call updateItem to reflect the changes
282  updateFilterByMap( false );
283  }
284 }
285 
287 {
288  return !mCustomLayerTree;
289 }
290 
292 {
293  mLegendFilterByMap = enabled;
294  updateFilterByMap( false );
295 }
296 
297 void QgsLayoutItemLegend::setTitle( const QString &t )
298 {
299  mTitle = t;
300  mSettings.setTitle( t );
301 
302  if ( mLayout && id().isEmpty() )
303  {
304  //notify the model that the display name has changed
305  mLayout->itemsModel()->updateItemDisplayName( this );
306  }
307 }
309 {
310  return mTitle;
311 }
312 
313 Qt::AlignmentFlag QgsLayoutItemLegend::titleAlignment() const
314 {
315  return mSettings.titleAlignment();
316 }
317 
318 void QgsLayoutItemLegend::setTitleAlignment( Qt::AlignmentFlag alignment )
319 {
320  mSettings.setTitleAlignment( alignment );
321 }
322 
324 {
325  return mSettings.rstyle( s );
326 }
327 
329 {
330  return mSettings.style( s );
331 }
332 
334 {
335  mSettings.setStyle( s, style );
336 }
337 
339 {
340  return mSettings.style( s ).font();
341 }
342 
344 {
345  rstyle( s ).setFont( f );
346 }
347 
349 {
350  rstyle( s ).setMargin( margin );
351 }
352 
354 {
355  rstyle( s ).setMargin( side, margin );
356 }
357 
359 {
360  return mSettings.lineSpacing();
361 }
362 
364 {
365  mSettings.setLineSpacing( spacing );
366 }
367 
369 {
370  return mSettings.boxSpace();
371 }
372 
374 {
375  mSettings.setBoxSpace( s );
376 }
377 
379 {
380  return mSettings.columnSpace();
381 }
382 
384 {
385  mSettings.setColumnSpace( s );
386 }
387 
389 {
390  return mSettings.fontColor();
391 }
392 
394 {
395  mSettings.setFontColor( c );
396 }
397 
399 {
400  return mSettings.symbolSize().width();
401 }
402 
404 {
405  mSettings.setSymbolSize( QSizeF( w, mSettings.symbolSize().height() ) );
406 }
407 
409 {
410  return mSettings.maximumSymbolSize();
411 }
412 
414 {
415  mSettings.setMaximumSymbolSize( size );
416 }
417 
419 {
420  return mSettings.minimumSymbolSize();
421 }
422 
424 {
425  mSettings.setMinimumSymbolSize( size );
426 }
427 
428 void QgsLayoutItemLegend::setSymbolAlignment( Qt::AlignmentFlag alignment )
429 {
430  mSettings.setSymbolAlignment( alignment );
431 }
432 
433 Qt::AlignmentFlag QgsLayoutItemLegend::symbolAlignment() const
434 {
435  return mSettings.symbolAlignment();
436 }
437 
439 {
440  return mSettings.symbolSize().height();
441 }
442 
444 {
445  mSettings.setSymbolSize( QSizeF( mSettings.symbolSize().width(), h ) );
446 }
447 
449 {
450  return mSettings.wmsLegendSize().width();
451 }
452 
454 {
455  mSettings.setWmsLegendSize( QSizeF( w, mSettings.wmsLegendSize().height() ) );
456 }
457 
459 {
460  return mSettings.wmsLegendSize().height();
461 }
463 {
464  mSettings.setWmsLegendSize( QSizeF( mSettings.wmsLegendSize().width(), h ) );
465 }
466 
467 void QgsLayoutItemLegend::setWrapString( const QString &t )
468 {
469  mSettings.setWrapChar( t );
470 }
471 
473 {
474  return mSettings.wrapChar();
475 }
476 
478 {
479  return mColumnCount;
480 }
481 
483 {
484  mColumnCount = c;
485  mSettings.setColumnCount( c );
486 }
487 
489 {
490  return mSettings.splitLayer();
491 }
492 
494 {
495  mSettings.setSplitLayer( s );
496 }
497 
499 {
500  return mSettings.equalColumnWidth();
501 }
502 
504 {
505  mSettings.setEqualColumnWidth( s );
506 }
507 
509 {
510  return mSettings.drawRasterStroke();
511 }
512 
514 {
515  mSettings.setDrawRasterStroke( enabled );
516 }
517 
519 {
520  return mSettings.rasterStrokeColor();
521 }
522 
523 void QgsLayoutItemLegend::setRasterStrokeColor( const QColor &color )
524 {
525  mSettings.setRasterStrokeColor( color );
526 }
527 
529 {
530  return mSettings.rasterStrokeWidth();
531 }
532 
534 {
535  mSettings.setRasterStrokeWidth( width );
536 }
537 
538 
540 {
541  adjustBoxSize();
542  updateFilterByMap( false );
543 }
544 
545 bool QgsLayoutItemLegend::writePropertiesToElement( QDomElement &legendElem, QDomDocument &doc, const QgsReadWriteContext &context ) const
546 {
547 
548  //write general properties
549  legendElem.setAttribute( QStringLiteral( "title" ), mTitle );
550  legendElem.setAttribute( QStringLiteral( "titleAlignment" ), QString::number( static_cast< int >( mSettings.titleAlignment() ) ) );
551  legendElem.setAttribute( QStringLiteral( "columnCount" ), QString::number( mColumnCount ) );
552  legendElem.setAttribute( QStringLiteral( "splitLayer" ), QString::number( mSettings.splitLayer() ) );
553  legendElem.setAttribute( QStringLiteral( "equalColumnWidth" ), QString::number( mSettings.equalColumnWidth() ) );
554 
555  legendElem.setAttribute( QStringLiteral( "boxSpace" ), QString::number( mSettings.boxSpace() ) );
556  legendElem.setAttribute( QStringLiteral( "columnSpace" ), QString::number( mSettings.columnSpace() ) );
557 
558  legendElem.setAttribute( QStringLiteral( "symbolWidth" ), QString::number( mSettings.symbolSize().width() ) );
559  legendElem.setAttribute( QStringLiteral( "symbolHeight" ), QString::number( mSettings.symbolSize().height() ) );
560  legendElem.setAttribute( QStringLiteral( "maxSymbolSize" ), QString::number( mSettings.maximumSymbolSize() ) );
561  legendElem.setAttribute( QStringLiteral( "minSymbolSize" ), QString::number( mSettings.minimumSymbolSize() ) );
562 
563  legendElem.setAttribute( QStringLiteral( "symbolAlignment" ), mSettings.symbolAlignment() );
564 
565  legendElem.setAttribute( QStringLiteral( "symbolAlignment" ), mSettings.symbolAlignment() );
566  legendElem.setAttribute( QStringLiteral( "lineSpacing" ), QString::number( mSettings.lineSpacing() ) );
567 
568  legendElem.setAttribute( QStringLiteral( "rasterBorder" ), mSettings.drawRasterStroke() );
569  legendElem.setAttribute( QStringLiteral( "rasterBorderColor" ), QgsSymbolLayerUtils::encodeColor( mSettings.rasterStrokeColor() ) );
570  legendElem.setAttribute( QStringLiteral( "rasterBorderWidth" ), QString::number( mSettings.rasterStrokeWidth() ) );
571 
572  legendElem.setAttribute( QStringLiteral( "wmsLegendWidth" ), QString::number( mSettings.wmsLegendSize().width() ) );
573  legendElem.setAttribute( QStringLiteral( "wmsLegendHeight" ), QString::number( mSettings.wmsLegendSize().height() ) );
574  legendElem.setAttribute( QStringLiteral( "wrapChar" ), mSettings.wrapChar() );
575  legendElem.setAttribute( QStringLiteral( "fontColor" ), mSettings.fontColor().name() );
576 
577  legendElem.setAttribute( QStringLiteral( "resizeToContents" ), mSizeToContents );
578 
579  if ( mMap )
580  {
581  legendElem.setAttribute( QStringLiteral( "map_uuid" ), mMap->uuid() );
582  }
583 
584  QDomElement legendStyles = doc.createElement( QStringLiteral( "styles" ) );
585  legendElem.appendChild( legendStyles );
586 
587  style( QgsLegendStyle::Title ).writeXml( QStringLiteral( "title" ), legendStyles, doc );
588  style( QgsLegendStyle::Group ).writeXml( QStringLiteral( "group" ), legendStyles, doc );
589  style( QgsLegendStyle::Subgroup ).writeXml( QStringLiteral( "subgroup" ), legendStyles, doc );
590  style( QgsLegendStyle::Symbol ).writeXml( QStringLiteral( "symbol" ), legendStyles, doc );
591  style( QgsLegendStyle::SymbolLabel ).writeXml( QStringLiteral( "symbolLabel" ), legendStyles, doc );
592 
593  if ( mCustomLayerTree )
594  {
595  // if not using auto-update - store the custom layer tree
596  mCustomLayerTree->writeXml( legendElem, context );
597  }
598 
599  if ( mLegendFilterByMap )
600  {
601  legendElem.setAttribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "1" ) );
602  }
603  legendElem.setAttribute( QStringLiteral( "legendFilterByAtlas" ), mFilterOutAtlas ? QStringLiteral( "1" ) : QStringLiteral( "0" ) );
604 
605  return true;
606 }
607 
608 bool QgsLayoutItemLegend::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context )
609 {
610  //read general properties
611  mTitle = itemElem.attribute( QStringLiteral( "title" ) );
612  mSettings.setTitle( mTitle );
613  if ( !itemElem.attribute( QStringLiteral( "titleAlignment" ) ).isEmpty() )
614  {
615  mSettings.setTitleAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "titleAlignment" ) ).toInt() ) );
616  }
617  int colCount = itemElem.attribute( QStringLiteral( "columnCount" ), QStringLiteral( "1" ) ).toInt();
618  if ( colCount < 1 ) colCount = 1;
619  mColumnCount = colCount;
620  mSettings.setColumnCount( mColumnCount );
621  mSettings.setSplitLayer( itemElem.attribute( QStringLiteral( "splitLayer" ), QStringLiteral( "0" ) ).toInt() == 1 );
622  mSettings.setEqualColumnWidth( itemElem.attribute( QStringLiteral( "equalColumnWidth" ), QStringLiteral( "0" ) ).toInt() == 1 );
623 
624  const QDomNodeList stylesNodeList = itemElem.elementsByTagName( QStringLiteral( "styles" ) );
625  if ( !stylesNodeList.isEmpty() )
626  {
627  const QDomNode stylesNode = stylesNodeList.at( 0 );
628  for ( int i = 0; i < stylesNode.childNodes().size(); i++ )
629  {
630  const QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
632  style.readXml( styleElem, doc, context );
633  const QString name = styleElem.attribute( QStringLiteral( "name" ) );
635  if ( name == QLatin1String( "title" ) ) s = QgsLegendStyle::Title;
636  else if ( name == QLatin1String( "group" ) ) s = QgsLegendStyle::Group;
637  else if ( name == QLatin1String( "subgroup" ) ) s = QgsLegendStyle::Subgroup;
638  else if ( name == QLatin1String( "symbol" ) ) s = QgsLegendStyle::Symbol;
639  else if ( name == QLatin1String( "symbolLabel" ) ) s = QgsLegendStyle::SymbolLabel;
640  else continue;
641  setStyle( s, style );
642  }
643  }
644 
645  //font color
646  QColor fontClr;
647  fontClr.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) );
648  mSettings.setFontColor( fontClr );
649 
650  //spaces
651  mSettings.setBoxSpace( itemElem.attribute( QStringLiteral( "boxSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
652  mSettings.setColumnSpace( itemElem.attribute( QStringLiteral( "columnSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
653 
654  mSettings.setSymbolSize( QSizeF( itemElem.attribute( QStringLiteral( "symbolWidth" ), QStringLiteral( "7.0" ) ).toDouble(), itemElem.attribute( QStringLiteral( "symbolHeight" ), QStringLiteral( "14.0" ) ).toDouble() ) );
655  mSettings.setSymbolAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "symbolAlignment" ), QString::number( Qt::AlignLeft ) ).toInt() ) );
656 
657  mSettings.setMaximumSymbolSize( itemElem.attribute( QStringLiteral( "maxSymbolSize" ), QStringLiteral( "0.0" ) ).toDouble() );
658  mSettings.setMinimumSymbolSize( itemElem.attribute( QStringLiteral( "minSymbolSize" ), QStringLiteral( "0.0" ) ).toDouble() );
659 
660  mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( QStringLiteral( "wmsLegendWidth" ), QStringLiteral( "50" ) ).toDouble(), itemElem.attribute( QStringLiteral( "wmsLegendHeight" ), QStringLiteral( "25" ) ).toDouble() ) );
661  mSettings.setLineSpacing( itemElem.attribute( QStringLiteral( "lineSpacing" ), QStringLiteral( "1.0" ) ).toDouble() );
662 
663  mSettings.setDrawRasterStroke( itemElem.attribute( QStringLiteral( "rasterBorder" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) );
664  mSettings.setRasterStrokeColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "rasterBorderColor" ), QStringLiteral( "0,0,0" ) ) ) );
665  mSettings.setRasterStrokeWidth( itemElem.attribute( QStringLiteral( "rasterBorderWidth" ), QStringLiteral( "0" ) ).toDouble() );
666 
667  mSettings.setWrapChar( itemElem.attribute( QStringLiteral( "wrapChar" ) ) );
668 
669  mSizeToContents = itemElem.attribute( QStringLiteral( "resizeToContents" ), QStringLiteral( "1" ) ) != QLatin1String( "0" );
670 
671  // map
672  mLegendFilterByMap = itemElem.attribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "0" ) ).toInt();
673 
674  mMapUuid.clear();
675  if ( !itemElem.attribute( QStringLiteral( "map_uuid" ) ).isEmpty() )
676  {
677  mMapUuid = itemElem.attribute( QStringLiteral( "map_uuid" ) );
678  }
679  // disconnect current map
680  setupMapConnections( mMap, false );
681  mMap = nullptr;
682 
683  mFilterOutAtlas = itemElem.attribute( QStringLiteral( "legendFilterByAtlas" ), QStringLiteral( "0" ) ).toInt();
684 
685  // QGIS >= 2.6
686  QDomElement layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree" ) );
687  if ( layerTreeElem.isNull() )
688  layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree-group" ) );
689 
690  if ( !layerTreeElem.isNull() )
691  {
692  std::unique_ptr< QgsLayerTree > tree( QgsLayerTree::readXml( layerTreeElem, context ) );
693  if ( mLayout )
694  tree->resolveReferences( mLayout->project(), true );
695  setCustomLayerTree( tree.release() );
696  }
697  else
698  setCustomLayerTree( nullptr );
699 
700  return true;
701 }
702 
704 {
705  if ( !id().isEmpty() )
706  {
707  return id();
708  }
709 
710  //if no id, default to portion of title text
711  QString text = mSettings.title();
712  if ( text.isEmpty() )
713  {
714  return tr( "<Legend>" );
715  }
716  if ( text.length() > 25 )
717  {
718  return tr( "%1…" ).arg( text.left( 25 ) );
719  }
720  else
721  {
722  return text;
723  }
724 }
725 
726 
727 void QgsLayoutItemLegend::setupMapConnections( QgsLayoutItemMap *map, bool connectSlots )
728 {
729  if ( !map )
730  return;
731 
732  if ( !connectSlots )
733  {
734  disconnect( map, &QObject::destroyed, this, &QgsLayoutItemLegend::invalidateCurrentMap );
735  disconnect( map, &QgsLayoutObject::changed, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
736  disconnect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
737  disconnect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
738  disconnect( map, &QgsLayoutItemMap::layerStyleOverridesChanged, this, &QgsLayoutItemLegend::mapLayerStyleOverridesChanged );
739  disconnect( map, &QgsLayoutItemMap::themeChanged, this, &QgsLayoutItemLegend::mapThemeChanged );
740  }
741  else
742  {
743  connect( map, &QObject::destroyed, this, &QgsLayoutItemLegend::invalidateCurrentMap );
744  connect( map, &QgsLayoutObject::changed, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
745  connect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
746  connect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
747  connect( map, &QgsLayoutItemMap::layerStyleOverridesChanged, this, &QgsLayoutItemLegend::mapLayerStyleOverridesChanged );
748  connect( map, &QgsLayoutItemMap::themeChanged, this, &QgsLayoutItemLegend::mapThemeChanged );
749  }
750 }
751 
753 {
754  if ( mMap )
755  {
756  setupMapConnections( mMap, false );
757  }
758 
759  mMap = map;
760 
761  if ( mMap )
762  {
763  setupMapConnections( mMap, true );
764  mapThemeChanged( mMap->themeToRender( mMap->createExpressionContext() ) );
765  }
766 
768 }
769 
770 void QgsLayoutItemLegend::invalidateCurrentMap()
771 {
772  setLinkedMap( nullptr );
773 }
774 
776 {
778 
779  bool forceUpdate = false;
780  //updates data defined properties and redraws item to match
781  if ( property == QgsLayoutObject::LegendTitle || property == QgsLayoutObject::AllProperties )
782  {
783  bool ok = false;
784  const QString t = mDataDefinedProperties.valueAsString( QgsLayoutObject::LegendTitle, context, mTitle, &ok );
785  if ( ok )
786  {
787  mSettings.setTitle( t );
788  forceUpdate = true;
789  }
790  }
792  {
793  bool ok = false;
794  const int cols = mDataDefinedProperties.valueAsInt( QgsLayoutObject::LegendColumnCount, context, mColumnCount, &ok );
795  if ( ok && cols >= 0 )
796  {
797  mSettings.setColumnCount( cols );
798  forceUpdate = true;
799  }
800  }
801  if ( forceUpdate )
802  {
803  adjustBoxSize();
804  update();
805  }
806 
808 }
809 
810 
811 void QgsLayoutItemLegend::updateFilterByMapAndRedraw()
812 {
813  updateFilterByMap( true );
814 }
815 
816 void QgsLayoutItemLegend::setModelStyleOverrides( const QMap<QString, QString> &overrides )
817 {
818  mLegendModel->setLayerStyleOverrides( overrides );
819  const QList< QgsLayerTreeLayer * > layers = mLegendModel->rootGroup()->findLayers();
820  for ( QgsLayerTreeLayer *nodeLayer : layers )
821  mLegendModel->refreshLayerLegend( nodeLayer );
822 
823 }
824 
825 void QgsLayoutItemLegend::clearLegendCachedData()
826 {
827  std::function< void( QgsLayerTreeNode * ) > clearNodeCache;
828  clearNodeCache = [&]( QgsLayerTreeNode * node )
829  {
830  mLegendModel->clearCachedData( node );
831  if ( QgsLayerTree::isGroup( node ) )
832  {
833  QgsLayerTreeGroup *group = QgsLayerTree::toGroup( node );
834  const QList< QgsLayerTreeNode * > children = group->children();
835  for ( QgsLayerTreeNode *child : children )
836  {
837  clearNodeCache( child );
838  }
839  }
840  };
841 
842  clearNodeCache( mLegendModel->rootGroup() );
843 }
844 
845 void QgsLayoutItemLegend::mapLayerStyleOverridesChanged()
846 {
847  if ( !mMap )
848  return;
849 
850  // map's style has been changed, so make sure to update the legend here
851  if ( mLegendFilterByMap )
852  {
853  // legend is being filtered by map, so we need to re run the hit test too
854  // as the style overrides may also have affected the visible symbols
855  updateFilterByMap( false );
856  }
857  else
858  {
859  setModelStyleOverrides( mMap->layerStyleOverrides() );
860  }
861 
862  adjustBoxSize();
863 
864  updateFilterByMap( false );
865 }
866 
867 void QgsLayoutItemLegend::mapThemeChanged( const QString &theme )
868 {
869  if ( mThemeName == theme )
870  return;
871 
872  mThemeName = theme;
873 
874  // map's theme has been changed, so make sure to update the legend here
875  if ( mLegendFilterByMap )
876  {
877  // legend is being filtered by map, so we need to re run the hit test too
878  // as the style overrides may also have affected the visible symbols
879  updateFilterByMap( false );
880  }
881  else
882  {
883  if ( mThemeName.isEmpty() )
884  {
885  setModelStyleOverrides( QMap<QString, QString>() );
886  }
887  else
888  {
889  // get style overrides for theme
890  const QMap<QString, QString> overrides = mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
891  setModelStyleOverrides( overrides );
892  }
893  }
894 
895  adjustBoxSize();
896 
898 }
899 
901 {
902  // ask for update
903  // the actual update will take place before the redraw.
904  // This is to avoid multiple calls to the filter
905  mFilterAskedForUpdate = true;
906 
907  if ( redraw )
908  update();
909 }
910 
911 void QgsLayoutItemLegend::doUpdateFilterByMap()
912 {
913  if ( mMap )
914  {
915  if ( !mThemeName.isEmpty() )
916  {
917  // get style overrides for theme
918  const QMap<QString, QString> overrides = mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
919  mLegendModel->setLayerStyleOverrides( overrides );
920  }
921  else
922  {
923  mLegendModel->setLayerStyleOverrides( mMap->layerStyleOverrides() );
924  }
925  }
926  else
927  mLegendModel->setLayerStyleOverrides( QMap<QString, QString>() );
928 
929 
930  const bool filterByExpression = QgsLayerTreeUtils::hasLegendFilterExpression( *( mCustomLayerTree ? mCustomLayerTree.get() : mLayout->project()->layerTreeRoot() ) );
931 
932  if ( mMap && ( mLegendFilterByMap || filterByExpression || mInAtlas ) )
933  {
934  const double dpi = mLayout->renderContext().dpi();
935 
936  const QgsRectangle requestRectangle = mMap->requestedExtent();
937 
938  QSizeF size( requestRectangle.width(), requestRectangle.height() );
939  size *= mLayout->convertFromLayoutUnits( mMap->mapUnitsToLayoutUnits(), QgsUnitTypes::LayoutMillimeters ).length() * dpi / 25.4;
940 
941  const QgsMapSettings ms = mMap->mapSettings( requestRectangle, size, dpi, true );
942 
943  QgsGeometry filterPolygon;
944  if ( mInAtlas )
945  {
946  filterPolygon = mLayout->reportContext().currentGeometry( mMap->crs() );
947  }
948  mLegendModel->setLegendFilter( &ms, /* useExtent */ mInAtlas || mLegendFilterByMap, filterPolygon, /* useExpressions */ true );
949  }
950  else
951  mLegendModel->setLegendFilterByMap( nullptr );
952 
953  clearLegendCachedData();
954  mForceResize = true;
955 }
956 
958 {
959  return mThemeName;
960 }
961 
963 {
964  mFilterOutAtlas = doFilter;
965 }
966 
968 {
969  return mFilterOutAtlas;
970 }
971 
972 void QgsLayoutItemLegend::onAtlasFeature()
973 {
974  if ( !mLayout || !mLayout->reportContext().feature().isValid() )
975  return;
976  mInAtlas = mFilterOutAtlas;
978 }
979 
980 void QgsLayoutItemLegend::onAtlasEnded()
981 {
982  mInAtlas = false;
984 }
985 
987 {
989 
990  // We only want the last scope from the map's expression context, as this contains
991  // the map specific variables. We don't want the rest of the map's context, because that
992  // will contain duplicate global, project, layout, etc scopes.
993  if ( mMap )
994  context.appendScope( mMap->createExpressionContext().popScope() );
995 
996  QgsExpressionContextScope *scope = new QgsExpressionContextScope( tr( "Legend Settings" ) );
997 
998  scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_title" ), title(), true ) );
999  scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_column_count" ), columnCount(), true ) );
1000  scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_split_layers" ), splitLayer(), true ) );
1001  scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_wrap_string" ), wrapString(), true ) );
1002  scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_filter_by_map" ), legendFilterByMapEnabled(), true ) );
1003  scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_filter_out_atlas" ), legendFilterOutAtlas(), true ) );
1004 
1005  context.appendScope( scope );
1006  return context;
1007 }
1008 
1010 {
1011  return MustPlaceInOwnLayer;
1012 }
1013 
1015 {
1016  std::function<bool( QgsLayerTreeGroup *group ) >visit;
1017 
1018  visit = [ =, &visit]( QgsLayerTreeGroup * group ) -> bool
1019  {
1020  const QList<QgsLayerTreeNode *> childNodes = group->children();
1021  for ( QgsLayerTreeNode *node : childNodes )
1022  {
1023  if ( QgsLayerTree::isGroup( node ) )
1024  {
1025  QgsLayerTreeGroup *nodeGroup = QgsLayerTree::toGroup( node );
1026  if ( !visit( nodeGroup ) )
1027  return false;
1028  }
1029  else if ( QgsLayerTree::isLayer( node ) )
1030  {
1031  QgsLayerTreeLayer *nodeLayer = QgsLayerTree::toLayer( node );
1032  if ( !nodeLayer->patchShape().isNull() )
1033  {
1034  QgsStyleLegendPatchShapeEntity entity( nodeLayer->patchShape() );
1035  if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity, uuid(), displayName() ) ) )
1036  return false;
1037  }
1038  const QList<QgsLayerTreeModelLegendNode *> legendNodes = mLegendModel->layerLegendNodes( nodeLayer );
1039  for ( QgsLayerTreeModelLegendNode *legendNode : legendNodes )
1040  {
1041  if ( QgsSymbolLegendNode *symbolNode = dynamic_cast< QgsSymbolLegendNode * >( legendNode ) )
1042  {
1043  if ( !symbolNode->patchShape().isNull() )
1044  {
1045  QgsStyleLegendPatchShapeEntity entity( symbolNode->patchShape() );
1046  if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity, uuid(), displayName() ) ) )
1047  return false;
1048  }
1049  }
1050  }
1051  }
1052  }
1053  return true;
1054  };
1055  return visit( mLegendModel->rootGroup( ) );
1056 }
1057 
1058 
1059 // -------------------------------------------------------------------------
1061 #include "qgsvectorlayer.h"
1062 #include "qgsmaplayerlegend.h"
1063 
1065  : QgsLayerTreeModel( rootNode, parent )
1066  , mLayoutLegend( layout )
1067 {
1070  connect( this, &QgsLegendModel::dataChanged, this, &QgsLegendModel::refreshLegend );
1071 }
1072 
1074  : QgsLayerTreeModel( rootNode )
1075  , mLayoutLegend( layout )
1076 {
1079  connect( this, &QgsLegendModel::dataChanged, this, &QgsLegendModel::refreshLegend );
1080 }
1081 
1082 QVariant QgsLegendModel::data( const QModelIndex &index, int role ) const
1083 {
1084  // handle custom layer node labels
1085 
1086  QgsLayerTreeNode *node = index2node( index );
1087  QgsLayerTreeLayer *nodeLayer = QgsLayerTree::isLayer( node ) ? QgsLayerTree::toLayer( node ) : nullptr;
1088  if ( nodeLayer && ( role == Qt::DisplayRole || role == Qt::EditRole ) )
1089  {
1090  QString name = node->customProperty( QStringLiteral( "cached_name" ) ).toString();
1091  if ( !name.isEmpty() )
1092  return name;
1093 
1094  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( nodeLayer->layer() );
1095 
1096  //finding the first label that is stored
1097  name = nodeLayer->customProperty( QStringLiteral( "legend/title-label" ) ).toString();
1098  if ( name.isEmpty() )
1099  name = nodeLayer->name();
1100  if ( name.isEmpty() )
1101  name = node->customProperty( QStringLiteral( "legend/title-label" ) ).toString();
1102  if ( name.isEmpty() )
1103  name = node->name();
1104  if ( nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt() )
1105  {
1106  if ( vlayer && vlayer->featureCount() >= 0 )
1107  {
1108  name += QStringLiteral( " [%1]" ).arg( vlayer->featureCount() );
1109  node->setCustomProperty( QStringLiteral( "cached_name" ), name );
1110  return name;
1111  }
1112  }
1113 
1114  const bool evaluate = ( vlayer && !nodeLayer->labelExpression().isEmpty() ) || name.contains( "[%" );
1115  if ( evaluate )
1116  {
1117  QgsExpressionContext expressionContext;
1118  if ( vlayer )
1119  {
1120  connect( vlayer, &QgsVectorLayer::symbolFeatureCountMapChanged, this, &QgsLegendModel::forceRefresh, Qt::UniqueConnection );
1121  // 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
1122  vlayer->countSymbolFeatures();
1123  }
1124 
1125  if ( mLayoutLegend )
1126  expressionContext = mLayoutLegend->createExpressionContext();
1127 
1128  const QList<QgsLayerTreeModelLegendNode *> legendnodes = layerLegendNodes( nodeLayer, false );
1129  if ( legendnodes.count() > 1 ) // evaluate all existing legend nodes but leave the name for the legend evaluator
1130  {
1131  for ( QgsLayerTreeModelLegendNode *treenode : legendnodes )
1132  {
1133  if ( QgsSymbolLegendNode *symnode = qobject_cast<QgsSymbolLegendNode *>( treenode ) )
1134  symnode->evaluateLabel( expressionContext );
1135  }
1136  }
1137  else if ( QgsSymbolLegendNode *symnode = qobject_cast<QgsSymbolLegendNode *>( legendnodes.first() ) )
1138  name = symnode->evaluateLabel( expressionContext );
1139  }
1140  node->setCustomProperty( QStringLiteral( "cached_name" ), name );
1141  return name;
1142  }
1143  return QgsLayerTreeModel::data( index, role );
1144 }
1145 
1146 Qt::ItemFlags QgsLegendModel::flags( const QModelIndex &index ) const
1147 {
1148  // make the legend nodes selectable even if they are not by default
1149  if ( index2legendNode( index ) )
1150  return QgsLayerTreeModel::flags( index ) | Qt::ItemIsSelectable;
1151 
1152  return QgsLayerTreeModel::flags( index );
1153 }
1154 
1155 QList<QgsLayerTreeModelLegendNode *> QgsLegendModel::layerLegendNodes( QgsLayerTreeLayer *nodeLayer, bool skipNodeEmbeddedInParent ) const
1156 {
1157  if ( !mLegend.contains( nodeLayer ) )
1158  return QList<QgsLayerTreeModelLegendNode *>();
1159 
1160  const LayerLegendData &data = mLegend[nodeLayer];
1161  QList<QgsLayerTreeModelLegendNode *> lst( data.activeNodes );
1162  if ( !skipNodeEmbeddedInParent && data.embeddedNodeInParent )
1163  lst.prepend( data.embeddedNodeInParent );
1164  return lst;
1165 }
1166 
1168 {
1169  node->removeCustomProperty( QStringLiteral( "cached_name" ) );
1170 }
1171 
1172 void QgsLegendModel::forceRefresh()
1173 {
1174  emit refreshLegend();
1175 }
1176 
1177 
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:125
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.
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.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
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 bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
Definition: qgslayertree.h:53
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
Definition: qgslayertree.h:75
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.
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 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...
void mapRotationChanged(double newRotation)
Emitted when the map's rotation changes.
QMap< QString, QString > layerStyleOverrides() const
Returns stored overrides of styles for layers.
QgsRectangle requestedExtent() const
Calculates the extent to request and the yShift of the top-left point in case of rotation.
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:45
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
Definition: qgslayoutitem.h:72
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: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)
QgsLegendStyle & rstyle(QgsLegendStyle::Style s)
Returns modifiable reference to the style for a legend component.
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).
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.
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:1345
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.
Definition: qgsunittypes.h:183
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:2065
#define Q_NOWARN_DEPRECATED_PUSH
Definition: qgis.h:2064
#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.