QGIS API Documentation  3.10.0-A Coruña (6c816b4204)
qgslayoutitemmap.h
Go to the documentation of this file.
1 /***************************************************************************
2  qgslayoutitemmap.h
3  -------------------
4  begin : July 2017
5  copyright : (C) 2017 by Nyall Dawson
6  email : nyall dot dawson at gmail dot com
7  ***************************************************************************/
8 /***************************************************************************
9  * *
10  * This program is free software; you can redistribute it and/or modify *
11  * it under the terms of the GNU General Public License as published by *
12  * the Free Software Foundation; either version 2 of the License, or *
13  * (at your option) any later version. *
14  * *
15  ***************************************************************************/
16 
17 #ifndef QGSLAYOUTITEMMAP_H
18 #define QGSLAYOUTITEMMAP_H
19 
20 #include "qgis_core.h"
21 #include "qgslayoutitem.h"
22 #include "qgslayoutitemregistry.h"
23 #include "qgsmaplayerref.h"
25 #include "qgslayoutitemmapgrid.h"
28 
29 class QgsAnnotation;
31 
38 class CORE_EXPORT QgsLayoutItemMap : public QgsLayoutItem
39 {
40 
41  Q_OBJECT
42 
43  public:
44 
49  {
51 
59 
65  Auto
66  };
67 
73  {
74  ShowPartialLabels = 1 << 0,
75  ShowUnplacedLabels = 1 << 1,
76  };
77  Q_DECLARE_FLAGS( MapItemFlags, MapItemFlag )
78 
79 
82  explicit QgsLayoutItemMap( QgsLayout *layout );
83  ~QgsLayoutItemMap() override;
84 
85  int type() const override;
86  QIcon icon() const override;
87  QgsLayoutItem::Flags itemFlags() const override;
88 
94  QgsLayoutItemMap::MapItemFlags mapFlags() const;
95 
101  void setMapFlags( QgsLayoutItemMap::MapItemFlags flags );
102 
106  void assignFreeId();
107 
108  //overridden to show "Map 1" type names
109  QString displayName() const override;
110 
116  static QgsLayoutItemMap *create( QgsLayout *layout ) SIP_FACTORY;
117 
118  // for now, map items behave a bit differently and don't implement draw. TODO - see if we can avoid this
119  void paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget ) override;
120  Q_DECL_DEPRECATED int numberExportLayers() const override SIP_DEPRECATED;
121  void startLayeredExport() override;
122  void stopLayeredExport() override;
123  bool nextExportPart() override;
124  ExportLayerBehavior exportLayerBehavior() const override;
125  QgsLayoutItem::ExportLayerDetail exportLayerDetails() const override;
126  void setFrameStrokeWidth( QgsLayoutMeasurement width ) override;
127 
133  double scale() const;
134 
142  void setScale( double scale, bool forceUpdate = true );
143 
151  void setExtent( const QgsRectangle &extent );
152 
160  void zoomToExtent( const QgsRectangle &extent );
161 
167  QgsRectangle extent() const;
168 
169 
177  QPolygonF visibleExtentPolygon() const;
178 
188 
197  QgsCoordinateReferenceSystem presetCrs() const { return mCrs; }
198 
206  void setCrs( const QgsCoordinateReferenceSystem &crs );
207 
216  bool keepLayerSet() const { return mKeepLayerSet; }
217 
226  void setKeepLayerSet( bool enabled ) { mKeepLayerSet = enabled; }
227 
234  QList<QgsMapLayer *> layers() const;
235 
242  void setLayers( const QList<QgsMapLayer *> &layers );
243 
248  bool keepLayerStyles() const { return mKeepLayerStyles; }
249 
254  void setKeepLayerStyles( bool enabled ) { mKeepLayerStyles = enabled; }
255 
260  QMap<QString, QString> layerStyleOverrides() const { return mLayerStyleOverrides; }
261 
266  void setLayerStyleOverrides( const QMap<QString, QString> &overrides );
267 
271  void storeCurrentLayerStyles();
272 
283  bool followVisibilityPreset() const { return mFollowVisibilityPreset; }
284 
288  void setFollowVisibilityPreset( bool follow ) { mFollowVisibilityPreset = follow; }
289 
295  QString followVisibilityPresetName() const { return mFollowVisibilityPresetName; }
296 
301  void setFollowVisibilityPresetName( const QString &name ) { mFollowVisibilityPresetName = name; }
302 
303  void moveContent( double dx, double dy ) override;
304  void setMoveContentPreviewOffset( double dx, double dy ) override;
305 
306  void zoomContent( double factor, QPointF point ) override;
307 
308 
310  bool containsWmsLayer() const;
311 
312  bool requiresRasterization() const override;
313  bool containsAdvancedEffects() const override;
314 
321  void setMapRotation( double rotation );
322 
331  double mapRotation( QgsLayoutObject::PropertyValueType valueType = QgsLayoutObject::EvaluatedValue ) const;
332 
337  void setDrawAnnotations( bool draw ) { mDrawAnnotations = draw; }
338 
343  bool drawAnnotations() const { return mDrawAnnotations; }
344 
345 
352  bool atlasDriven() const { return mAtlasDriven; }
353 
360  void setAtlasDriven( bool enabled );
361 
371  AtlasScalingMode atlasScalingMode() const { return mAtlasScalingMode; }
372 
382  void setAtlasScalingMode( AtlasScalingMode mode ) { mAtlasScalingMode = mode; }
383 
395 
403  void setAtlasMargin( double margin ) { mAtlasMargin = margin; }
404 
410  QgsLayoutItemMapGridStack *grids() { return mGridStack.get(); }
411 
416  QgsLayoutItemMapGrid *grid();
417 
424  QgsLayoutItemMapOverviewStack *overviews() { return mOverviewStack.get(); }
425 
431  QgsLayoutItemMapOverview *overview();
432 
443  QgsLayoutMeasurement labelMargin() const;
444 
455  void setLabelMargin( const QgsLayoutMeasurement &margin );
456 
458 
464  double mapUnitsToLayoutUnits() const;
465 
473  QgsMapSettings mapSettings( const QgsRectangle &extent, QSizeF size, double dpi, bool includeLayerSettings ) const;
474 
475  void finalizeRestoreFromXml() override;
476 
481  QList<QgsMapLayer *> layersToRender( const QgsExpressionContext *context = nullptr ) const;
482 
494  void addLabelBlockingItem( QgsLayoutItem *item );
495 
507  void removeLabelBlockingItem( QgsLayoutItem *item );
508 
520  bool isLabelBlockingItem( QgsLayoutItem *item ) const;
521 
526  QgsMapRendererJob::Errors renderingErrors() const { return mRenderingErrors; }
527 
528  bool accept( QgsStyleEntityVisitorInterface *visitor ) const override;
529 
542  void addRenderedFeatureHandler( QgsRenderedFeatureHandlerInterface *handler );
543 
550  void removeRenderedFeatureHandler( QgsRenderedFeatureHandlerInterface *handler );
551 
555  QTransform layoutToMapCoordsTransform() const;
556 
557  protected:
558 
559  void draw( QgsLayoutItemRenderContext &context ) override;
560  bool writePropertiesToElement( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const override;
561  bool readPropertiesFromElement( const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context ) override;
562 
564  bool isDrawing() const {return mDrawing;}
565 
566  // In case of annotations, the bounding rectangle can be larger than the map item rectangle
567  QRectF boundingRect() const override;
568 
570  QPolygonF transformedMapPolygon() const;
571 
573  QPointF mapToItemCoords( QPointF mapCoords ) const;
574 
578  QgsRectangle requestedExtent() const;
579 
580  signals:
581 
587  void extentChanged();
588 
594  void mapRotationChanged( double newRotation );
595 
597  void preparedForAtlas();
598 
603  void layerStyleOverridesChanged();
604 
605  public slots:
606 
607  void refresh() override;
608 
609  void invalidateCache() override;
610 
612  void updateBoundingRect();
613 
615 
616  private slots:
617  void layersAboutToBeRemoved( const QList<QgsMapLayer *> &layers );
618 
619  void painterJobFinished();
620 
621  void shapeChanged();
622 
623  void mapThemeChanged( const QString &theme );
624 
626  void recreateCachedImageInBackground();
627 
628  void updateAtlasFeature();
629  private:
630 
631  QgsLayoutItemMap::MapItemFlags mMapFlags = nullptr;
632 
634  int mMapId = 1;
635 
636  std::unique_ptr< QgsLayoutItemMapGridStack > mGridStack;
637  std::unique_ptr< QgsLayoutItemMapOverviewStack > mOverviewStack;
638 
639  // Map region in map units really used for rendering
640  // It can be the same as mUserExtent, but it can be bigger in on dimension if mCalculate==Scale,
641  // so that full rectangle in paper is used.
642  QgsRectangle mExtent;
643 
646 
647  // Current temporary map region in map units. This is overwritten when atlas feature changes. It's also
648  // used when the user changes the map extent and an atlas preview is enabled. This allows the user
649  // to manually tweak each atlas preview page without affecting the actual original map extent.
650  QgsRectangle mAtlasFeatureExtent;
651 
652  // We have two images used for rendering/storing cached map images.
653  // the first (mCacheFinalImage) is used ONLY for storing the most recent completed map render. It's always
654  // used when drawing map item previews. The second (mCacheRenderingImage) is used temporarily while
655  // rendering a new preview image in the background. If (and only if) the background render completes, then
656  // mCacheRenderingImage is pushed into mCacheFinalImage, and used from then on when drawing the item preview.
657  // This ensures that something is always shown in the map item, even while refreshing the preview image in the
658  // background
659  std::unique_ptr< QImage > mCacheFinalImage;
660  std::unique_ptr< QImage > mCacheRenderingImage;
661  bool mUpdatesEnabled = true;
662 
664  bool mCacheInvalidated = true;
665 
667  int mNumCachedLayers;
668 
669  // Set to true if in state of drawing. Concurrent requests to draw method are returned if set to true
670  bool mDrawing = false;
671 
672  QTimer *mBackgroundUpdateTimer = nullptr;
673  double mPreviewScaleFactor = 0;
674 
675  bool mDrawingPreview = false;
676 
678  double mXOffset = 0.0;
680  double mYOffset = 0.0;
681 
682  double mLastRenderedImageOffsetX = 0.0;
683  double mLastRenderedImageOffsetY = 0.0;
684 
686  double mMapRotation = 0;
687 
691  double mEvaluatedMapRotation = 0;
692 
694  bool mKeepLayerSet = false;
695 
697  QList< QgsMapLayerRef > mLayers;
698 
699  bool mKeepLayerStyles = false;
701  QMap<QString, QString> mLayerStyleOverrides;
702 
704  mutable QString mCachedLayerStyleOverridesPresetName;
706  mutable QMap<QString, QString> mCachedPresetLayerStyleOverrides;
707 
712  bool mFollowVisibilityPreset = false;
713 
717  QString mFollowVisibilityPresetName;
718 
726  void drawMap( QPainter *painter, const QgsRectangle &extent, QSizeF size, double dpi );
727 
729  void connectUpdateSlot();
730 
732  void syncLayerSet();
733 
735  const QgsLayoutItemMapGrid *constFirstMapGrid() const;
736 
738  const QgsLayoutItemMapOverview *constFirstMapOverview() const;
739 
744  QList< QgsLabelBlockingRegion > createLabelBlockingRegions( const QgsMapSettings &mapSettings ) const;
745 
747  QRectF mCurrentRectangle;
749  bool mDrawAnnotations = true;
750 
752  bool mAtlasDriven = false;
754  AtlasScalingMode mAtlasScalingMode = Auto;
756  double mAtlasMargin = 0.10;
757 
758  std::unique_ptr< QPainter > mPainter;
759  std::unique_ptr< QgsMapRendererCustomPainterJob > mPainterJob;
760  bool mPainterCancelWait = false;
761 
762  QgsLayoutMeasurement mLabelMargin{ 0 };
763  QgsLayoutMeasurement mEvaluatedLabelMargin{ 0 };
764 
765  QStringList mBlockingLabelItemUuids;
766  QList< QPointer< QgsLayoutItem > > mBlockingLabelItems;
767 
769  QgsMapRendererJob::Errors mRenderingErrors;
770 
771  QList< QgsRenderedFeatureHandlerInterface * > mRenderedFeatureHandlers;
772 
773  std::unique_ptr< QgsMapRendererStagedRenderJob > mStagedRendererJob;
774 
775  void init();
776 
778  void updateToolTip();
779 
780  QString themeToRender( const QgsExpressionContext &context ) const;
781 
783  QMap<QString, QString> layerStyleOverridesToRender( const QgsExpressionContext &context ) const;
784 
786  QgsRectangle transformedExtent() const;
787 
789  void mapPolygon( const QgsRectangle &extent, QPolygonF &poly ) const;
790 
796  void transformShift( double &xShift, double &yShift ) const;
797 
798  void drawAnnotations( QPainter *painter );
799  void drawAnnotation( const QgsAnnotation *item, QgsRenderContext &context );
800  QPointF layoutMapPosForItem( const QgsAnnotation *item ) const;
801 
802  void drawMapFrame( QPainter *p );
803  void drawMapBackground( QPainter *p );
804 
805  enum PartType
806  {
807  Start,
808  Background,
809  Layer,
810  Grid,
811  OverviewMapExtent,
812  Frame,
813  SelectionBoxes,
814  End,
815  NotLayered,
816  };
817 
819  bool shouldDrawPart( PartType part ) const;
820 
821  PartType mCurrentExportPart = NotLayered;
822  QStringList mExportThemes;
823  QStringList::iterator mExportThemeIt;
824 
829  void refreshMapExtents( const QgsExpressionContext *context = nullptr );
830 
831  void refreshLabelMargin( bool updateItem );
832 
833  QgsRectangle computeAtlasRectangle();
834 
835  void createStagedRenderJob( const QgsRectangle &extent, const QSizeF size, double dpi );
836 
837  friend class QgsLayoutItemMapGrid;
839  friend class QgsLayoutItemLegend;
840  friend class TestQgsLayoutMap;
842  friend class QgsGeoPdfRenderedFeatureHandler;
843 
844 };
845 
846 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsLayoutItemMap::MapItemFlags )
847 
848 #endif //QGSLAYOUTITEMMAP_H
The class is used as a container of context for various read/write operations on other objects...
bool isDrawing() const
True if a draw is already in progress.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
bool followVisibilityPreset() const
Returns whether the map should follow a map theme.
virtual QIcon icon() const
Returns the item&#39;s icon.
void setFollowVisibilityPresetName(const QString &name)
Sets preset name for map rendering.
A rectangle specified with double values.
Definition: qgsrectangle.h:41
AtlasScalingMode atlasScalingMode() const
Returns the current atlas scaling mode.
Base class for graphical items within a QgsLayout.
An individual overview which is drawn above the map content in a QgsLayoutItemMap, and shows the extent of another QgsLayoutItemMap.
int type() const override
Returns a unique graphics item type identifier.
virtual bool containsAdvancedEffects() const
Returns true if the item contains contents with blend modes or transparency effects which can only be...
void setKeepLayerStyles(bool enabled)
Sets whether current styles of layers should be overridden by previously stored styles.
virtual Q_DECL_DEPRECATED int numberExportLayers() const
Returns the number of layers that this item requires for exporting during layered exports (e...
bool keepLayerStyles() const
Returns whether current styles of layers should be overridden by previously stored styles...
A collection of overviews which are drawn above the map content in a QgsLayoutItemMap.
bool drawAnnotations() const
Returns whether annotations are drawn within the map.
void setKeepLayerSet(bool enabled)
Sets whether the stored layer set should be used or the current layer set of the associated project...
const QgsCoordinateReferenceSystem & crs
An interface for classes which can visit style entity (e.g.
virtual void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties)
Refreshes a data defined property for the item by reevaluating the property&#39;s value and redrawing the...
Abstract base class for annotation items which are drawn over a map.
Definition: qgsannotation.h:49
The QgsMapSettings class contains configuration for rendering of the map.
PropertyValueType
Specifies whether the value returned by a function should be the original, user set value...
virtual void invalidateCache()
Forces a deferred update of any cached image the item uses.
Layout graphical items for displaying a map.
A collection of grids which is drawn above the map content in a QgsLayoutItemMap. ...
This class provides a method of storing measurements for use in QGIS layouts using a variety of diffe...
virtual bool readPropertiesFromElement(const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context)
Sets item state from a DOM element.
void paint(QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget) override
Handles preparing a paint surface for the layout item and painting the item&#39;s content.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
An interface for classes which provider custom handlers for features rendered as part of a map render...
QgsMapRendererJob::Errors renderingErrors() const
Returns map rendering errors.
MapItemFlag
Various flags that affect drawing of map items.
#define SIP_FACTORY
Definition: qgis_sip.h:76
virtual bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified style entity visitor, causing it to visit all style entities associated with th...
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
Definition: qgslayout.h:49
#define SIP_DEPRECATED
Definition: qgis_sip.h:106
void setAtlasScalingMode(AtlasScalingMode mode)
Sets the current atlas scaling mode.
virtual bool requiresRasterization() const
Returns true if the item is drawn in such a way that forces the whole layout to be rasterized when ex...
virtual Flags itemFlags() const
Returns the item&#39;s flags, which indicate how the item behaves.
An individual grid which is drawn above the map content in a QgsLayoutItemMap.
bool keepLayerSet() const
Returns whether a stored layer set should be used or the current layer set from the project associate...
Contains settings and helpers relating to a render of a QgsLayoutItem.
Definition: qgslayoutitem.h:44
virtual void finalizeRestoreFromXml()
Called after all pending items have been restored from XML.
void setAtlasMargin(double margin)
Sets the margin size (percentage) used when the map is in atlas mode.
virtual QString displayName() const
Gets item display name.
void setFollowVisibilityPreset(bool follow)
Sets whether the map should follow a map theme.
QgsCompositionConverter class converts a QGIS 2.x composition to a QGIS 3.x layout.
Return the current evaluated value for the property.
Contains information about the context of a rendering operation.
ExportLayerBehavior
Behavior of item when exporting to layered outputs.
QList< QgsMapRendererJob::Error > Errors
void setDrawAnnotations(bool draw)
Sets whether annotations are drawn within the map.
virtual void setMoveContentPreviewOffset(double dx, double dy)
Sets temporary offset for the item, by a specified dx and dy in layout units.
The current scale of the map is used for each feature of the atlas.
virtual void moveContent(double dx, double dy)
Moves the content of the item, by a specified dx and dy in layout units.
This class represents a coordinate reference system (CRS).
virtual void zoomContent(double factor, QPointF point)
Zooms content of item.
virtual bool writePropertiesToElement(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Stores item state within an XML DOM element.
virtual void draw(QgsLayoutItemRenderContext &context)=0
Draws the item&#39;s contents using the specified item render context.
bool atlasDriven() const
Returns whether the map extent is set to follow the current atlas feature.
AtlasScalingMode
Scaling modes used for the serial rendering (atlas)
A layout item subclass for map legends.
QString followVisibilityPresetName() const
Preset name that decides which layers and layer styles are used for map rendering.
Contains details of a particular export layer relating to a layout item.
DataDefinedProperty
Data defined properties for different item types.
void refresh() override
Refreshes the item, causing a recalculation of any property overrides and recalculation of its positi...
QgsLayoutItemMapOverviewStack * overviews()
Returns the map item&#39;s overview stack, which is used to control how overviews are drawn over the map&#39;...
QgsLayoutItemMapGridStack * grids()
Returns the map item&#39;s grid stack, which is used to control how grids are drawn over the map&#39;s conten...
A scale is chosen from the predefined scales.
All properties for item.
QMap< QString, QString > layerStyleOverrides() const
Returns stored overrides of styles for layers.