QGIS API Documentation  3.13.0-Master (b73bd58cfb)
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 );
289 
297  QString followVisibilityPresetName() const { return mFollowVisibilityPresetName; }
298 
305  void setFollowVisibilityPresetName( const QString &name );
306 
307  void moveContent( double dx, double dy ) override;
308  void setMoveContentPreviewOffset( double dx, double dy ) override;
309 
310  void zoomContent( double factor, QPointF point ) override;
311 
312 
314  bool containsWmsLayer() const;
315 
316  bool requiresRasterization() const override;
317  bool containsAdvancedEffects() const override;
318 
325  void setMapRotation( double rotation );
326 
335  double mapRotation( QgsLayoutObject::PropertyValueType valueType = QgsLayoutObject::EvaluatedValue ) const;
336 
341  void setDrawAnnotations( bool draw ) { mDrawAnnotations = draw; }
342 
347  bool drawAnnotations() const { return mDrawAnnotations; }
348 
349 
356  bool atlasDriven() const { return mAtlasDriven; }
357 
364  void setAtlasDriven( bool enabled );
365 
375  AtlasScalingMode atlasScalingMode() const { return mAtlasScalingMode; }
376 
386  void setAtlasScalingMode( AtlasScalingMode mode ) { mAtlasScalingMode = mode; }
387 
399 
407  void setAtlasMargin( double margin ) { mAtlasMargin = margin; }
408 
414  QgsLayoutItemMapGridStack *grids() { return mGridStack.get(); }
415 
420  QgsLayoutItemMapGrid *grid();
421 
428  QgsLayoutItemMapOverviewStack *overviews() { return mOverviewStack.get(); }
429 
435  QgsLayoutItemMapOverview *overview();
436 
447  QgsLayoutMeasurement labelMargin() const;
448 
459  void setLabelMargin( const QgsLayoutMeasurement &margin );
460 
462 
468  double mapUnitsToLayoutUnits() const;
469 
477  QgsMapSettings mapSettings( const QgsRectangle &extent, QSizeF size, double dpi, bool includeLayerSettings ) const;
478 
479  void finalizeRestoreFromXml() override;
480 
485  QList<QgsMapLayer *> layersToRender( const QgsExpressionContext *context = nullptr ) const;
486 
498  void addLabelBlockingItem( QgsLayoutItem *item );
499 
511  void removeLabelBlockingItem( QgsLayoutItem *item );
512 
524  bool isLabelBlockingItem( QgsLayoutItem *item ) const;
525 
530  QgsMapRendererJob::Errors renderingErrors() const { return mRenderingErrors; }
531 
532  bool accept( QgsStyleEntityVisitorInterface *visitor ) const override;
533 
546  void addRenderedFeatureHandler( QgsRenderedFeatureHandlerInterface *handler );
547 
554  void removeRenderedFeatureHandler( QgsRenderedFeatureHandlerInterface *handler );
555 
559  QTransform layoutToMapCoordsTransform() const;
560 
561  protected:
562 
563  void draw( QgsLayoutItemRenderContext &context ) override;
564  bool writePropertiesToElement( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const override;
565  bool readPropertiesFromElement( const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context ) override;
566 
568  bool isDrawing() const {return mDrawing;}
569 
570  // In case of annotations, the bounding rectangle can be larger than the map item rectangle
571  QRectF boundingRect() const override;
572 
574  QPolygonF transformedMapPolygon() const;
575 
577  QPointF mapToItemCoords( QPointF mapCoords ) const;
578 
582  QgsRectangle requestedExtent() const;
583 
584  signals:
585 
591  void extentChanged();
592 
598  void mapRotationChanged( double newRotation );
599 
601  void preparedForAtlas();
602 
607  void layerStyleOverridesChanged();
608 
617  void themeChanged( const QString &theme );
618 
619  public slots:
620 
621  void refresh() override;
622 
623  void invalidateCache() override;
624 
626  void updateBoundingRect();
627 
629 
630  private slots:
631  void layersAboutToBeRemoved( const QList<QgsMapLayer *> &layers );
632 
633  void painterJobFinished();
634 
635  void shapeChanged();
636 
637  void mapThemeChanged( const QString &theme );
638 
640  void recreateCachedImageInBackground();
641 
642  void updateAtlasFeature();
643  private:
644 
645  QgsLayoutItemMap::MapItemFlags mMapFlags = nullptr;
646 
648  int mMapId = 1;
649 
650  std::unique_ptr< QgsLayoutItemMapGridStack > mGridStack;
651  std::unique_ptr< QgsLayoutItemMapOverviewStack > mOverviewStack;
652 
653  // Map region in map units really used for rendering
654  // It can be the same as mUserExtent, but it can be bigger in on dimension if mCalculate==Scale,
655  // so that full rectangle in paper is used.
656  QgsRectangle mExtent;
657 
660 
661  // Current temporary map region in map units. This is overwritten when atlas feature changes. It's also
662  // used when the user changes the map extent and an atlas preview is enabled. This allows the user
663  // to manually tweak each atlas preview page without affecting the actual original map extent.
664  QgsRectangle mAtlasFeatureExtent;
665 
666  // We have two images used for rendering/storing cached map images.
667  // the first (mCacheFinalImage) is used ONLY for storing the most recent completed map render. It's always
668  // used when drawing map item previews. The second (mCacheRenderingImage) is used temporarily while
669  // rendering a new preview image in the background. If (and only if) the background render completes, then
670  // mCacheRenderingImage is pushed into mCacheFinalImage, and used from then on when drawing the item preview.
671  // This ensures that something is always shown in the map item, even while refreshing the preview image in the
672  // background
673  std::unique_ptr< QImage > mCacheFinalImage;
674  std::unique_ptr< QImage > mCacheRenderingImage;
675  bool mUpdatesEnabled = true;
676 
678  bool mCacheInvalidated = true;
679 
681  int mNumCachedLayers;
682 
683  // Set to true if in state of drawing. Concurrent requests to draw method are returned if set to true
684  bool mDrawing = false;
685 
686  QTimer *mBackgroundUpdateTimer = nullptr;
687  double mPreviewScaleFactor = 0;
688 
689  bool mDrawingPreview = false;
690 
692  double mXOffset = 0.0;
694  double mYOffset = 0.0;
695 
696  double mLastRenderedImageOffsetX = 0.0;
697  double mLastRenderedImageOffsetY = 0.0;
698 
700  double mMapRotation = 0;
701 
705  double mEvaluatedMapRotation = 0;
706 
708  bool mKeepLayerSet = false;
709 
711  QList< QgsMapLayerRef > mLayers;
712 
713  bool mKeepLayerStyles = false;
715  QMap<QString, QString> mLayerStyleOverrides;
716 
718  mutable QString mCachedLayerStyleOverridesPresetName;
720  mutable QMap<QString, QString> mCachedPresetLayerStyleOverrides;
721 
726  bool mFollowVisibilityPreset = false;
727 
731  QString mFollowVisibilityPresetName;
732 
734  QString mLastEvaluatedThemeName;
735 
743  void drawMap( QPainter *painter, const QgsRectangle &extent, QSizeF size, double dpi );
744 
746  void connectUpdateSlot();
747 
749  void syncLayerSet();
750 
752  const QgsLayoutItemMapGrid *constFirstMapGrid() const;
753 
755  const QgsLayoutItemMapOverview *constFirstMapOverview() const;
756 
761  QList< QgsLabelBlockingRegion > createLabelBlockingRegions( const QgsMapSettings &mapSettings ) const;
762 
764  QRectF mCurrentRectangle;
766  bool mDrawAnnotations = true;
767 
769  bool mAtlasDriven = false;
771  AtlasScalingMode mAtlasScalingMode = Auto;
773  double mAtlasMargin = 0.10;
774 
775  std::unique_ptr< QPainter > mPainter;
776  std::unique_ptr< QgsMapRendererCustomPainterJob > mPainterJob;
777  bool mPainterCancelWait = false;
778 
779  QgsLayoutMeasurement mLabelMargin{ 0 };
780  QgsLayoutMeasurement mEvaluatedLabelMargin{ 0 };
781 
782  QStringList mBlockingLabelItemUuids;
783  QList< QPointer< QgsLayoutItem > > mBlockingLabelItems;
784 
786  QgsMapRendererJob::Errors mRenderingErrors;
787 
788  QList< QgsRenderedFeatureHandlerInterface * > mRenderedFeatureHandlers;
789 
790  std::unique_ptr< QgsMapRendererStagedRenderJob > mStagedRendererJob;
791 
792  void init();
793 
795  void updateToolTip();
796 
797  QString themeToRender( const QgsExpressionContext &context ) const;
798 
800  QMap<QString, QString> layerStyleOverridesToRender( const QgsExpressionContext &context ) const;
801 
803  QgsRectangle transformedExtent() const;
804 
806  void mapPolygon( const QgsRectangle &extent, QPolygonF &poly ) const;
807 
813  void transformShift( double &xShift, double &yShift ) const;
814 
815  void drawAnnotations( QPainter *painter );
816  void drawAnnotation( const QgsAnnotation *item, QgsRenderContext &context );
817  QPointF layoutMapPosForItem( const QgsAnnotation *item ) const;
818 
819  void drawMapFrame( QPainter *p );
820  void drawMapBackground( QPainter *p );
821 
822  enum PartType
823  {
824  Start,
825  Background,
826  Layer,
827  Grid,
828  OverviewMapExtent,
829  Frame,
830  SelectionBoxes,
831  End,
832  NotLayered,
833  };
834 
836  bool shouldDrawPart( PartType part ) const;
837 
838  PartType mCurrentExportPart = NotLayered;
839  QStringList mExportThemes;
840  QStringList::iterator mExportThemeIt;
841 
846  void refreshMapExtents( const QgsExpressionContext *context = nullptr );
847 
848  void refreshLabelMargin( bool updateItem );
849 
850  QgsRectangle computeAtlasRectangle();
851 
852  void createStagedRenderJob( const QgsRectangle &extent, const QSizeF size, double dpi );
853 
854  friend class QgsLayoutItemMapGrid;
856  friend class QgsLayoutItemLegend;
857  friend class TestQgsLayoutMap;
859  friend class QgsGeoPdfRenderedFeatureHandler;
860 
861 };
862 
863 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsLayoutItemMap::MapItemFlags )
864 
865 #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.
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.
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.