QGIS API Documentation  3.8.0-Zanzibar (11aff65)
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"
27 
28 class QgsAnnotation;
29 
36 class CORE_EXPORT QgsLayoutItemMap : public QgsLayoutItem
37 {
38 
39  Q_OBJECT
40 
41  public:
42 
47  {
49 
57 
63  Auto
64  };
65 
71  {
72  ShowPartialLabels = 1 << 0,
73  };
74  Q_DECLARE_FLAGS( MapItemFlags, MapItemFlag )
75 
76 
79  explicit QgsLayoutItemMap( QgsLayout *layout );
80  ~QgsLayoutItemMap() override;
81 
82  int type() const override;
83  QIcon icon() const override;
84  QgsLayoutItem::Flags itemFlags() const override;
85 
91  QgsLayoutItemMap::MapItemFlags mapFlags() const;
92 
98  void setMapFlags( QgsLayoutItemMap::MapItemFlags flags );
99 
103  void assignFreeId();
104 
105  //overridden to show "Map 1" type names
106  QString displayName() const override;
107 
113  static QgsLayoutItemMap *create( QgsLayout *layout ) SIP_FACTORY;
114 
115  // for now, map items behave a bit differently and don't implement draw. TODO - see if we can avoid this
116  void paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget ) override;
117  int numberExportLayers() const override;
118  void setFrameStrokeWidth( QgsLayoutMeasurement width ) override;
119 
125  double scale() const;
126 
134  void setScale( double scale, bool forceUpdate = true );
135 
143  void setExtent( const QgsRectangle &extent );
144 
152  void zoomToExtent( const QgsRectangle &extent );
153 
159  QgsRectangle extent() const;
160 
161 
169  QPolygonF visibleExtentPolygon() const;
170 
180 
189  QgsCoordinateReferenceSystem presetCrs() const { return mCrs; }
190 
198  void setCrs( const QgsCoordinateReferenceSystem &crs );
199 
208  bool keepLayerSet() const { return mKeepLayerSet; }
209 
218  void setKeepLayerSet( bool enabled ) { mKeepLayerSet = enabled; }
219 
226  QList<QgsMapLayer *> layers() const;
227 
234  void setLayers( const QList<QgsMapLayer *> &layers );
235 
240  bool keepLayerStyles() const { return mKeepLayerStyles; }
241 
246  void setKeepLayerStyles( bool enabled ) { mKeepLayerStyles = enabled; }
247 
252  QMap<QString, QString> layerStyleOverrides() const { return mLayerStyleOverrides; }
253 
258  void setLayerStyleOverrides( const QMap<QString, QString> &overrides );
259 
263  void storeCurrentLayerStyles();
264 
275  bool followVisibilityPreset() const { return mFollowVisibilityPreset; }
276 
280  void setFollowVisibilityPreset( bool follow ) { mFollowVisibilityPreset = follow; }
281 
287  QString followVisibilityPresetName() const { return mFollowVisibilityPresetName; }
288 
293  void setFollowVisibilityPresetName( const QString &name ) { mFollowVisibilityPresetName = name; }
294 
295  void moveContent( double dx, double dy ) override;
296  void setMoveContentPreviewOffset( double dx, double dy ) override;
297 
298  void zoomContent( double factor, QPointF point ) override;
299 
300 
302  bool containsWmsLayer() const;
303 
304  bool requiresRasterization() const override;
305  bool containsAdvancedEffects() const override;
306 
313  void setMapRotation( double rotation );
314 
323  double mapRotation( QgsLayoutObject::PropertyValueType valueType = QgsLayoutObject::EvaluatedValue ) const;
324 
329  void setDrawAnnotations( bool draw ) { mDrawAnnotations = draw; }
330 
335  bool drawAnnotations() const { return mDrawAnnotations; }
336 
337 
344  bool atlasDriven() const { return mAtlasDriven; }
345 
352  void setAtlasDriven( bool enabled );
353 
363  AtlasScalingMode atlasScalingMode() const { return mAtlasScalingMode; }
364 
374  void setAtlasScalingMode( AtlasScalingMode mode ) { mAtlasScalingMode = mode; }
375 
387 
395  void setAtlasMargin( double margin ) { mAtlasMargin = margin; }
396 
402  QgsLayoutItemMapGridStack *grids() { return mGridStack.get(); }
403 
408  QgsLayoutItemMapGrid *grid();
409 
416  QgsLayoutItemMapOverviewStack *overviews() { return mOverviewStack.get(); }
417 
423  QgsLayoutItemMapOverview *overview();
424 
435  QgsLayoutMeasurement labelMargin() const;
436 
447  void setLabelMargin( const QgsLayoutMeasurement &margin );
448 
450 
456  double mapUnitsToLayoutUnits() const;
457 
465  QgsMapSettings mapSettings( const QgsRectangle &extent, QSizeF size, double dpi, bool includeLayerSettings ) const;
466 
467  void finalizeRestoreFromXml() override;
468 
473  QList<QgsMapLayer *> layersToRender( const QgsExpressionContext *context = nullptr ) const;
474 
486  void addLabelBlockingItem( QgsLayoutItem *item );
487 
499  void removeLabelBlockingItem( QgsLayoutItem *item );
500 
512  bool isLabelBlockingItem( QgsLayoutItem *item ) const;
513 
518  QgsMapRendererJob::Errors renderingErrors() const { return mRenderingErrors; }
519 
520  protected:
521 
522  void draw( QgsLayoutItemRenderContext &context ) override;
523  bool writePropertiesToElement( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const override;
524  bool readPropertiesFromElement( const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context ) override;
525 
527  bool isDrawing() const {return mDrawing;}
528 
529  // In case of annotations, the bounding rectangle can be larger than the map item rectangle
530  QRectF boundingRect() const override;
531 
533  QPolygonF transformedMapPolygon() const;
534 
536  QPointF mapToItemCoords( QPointF mapCoords ) const;
537 
541  QgsRectangle requestedExtent() const;
542 
543  signals:
544 
550  void extentChanged();
551 
557  void mapRotationChanged( double newRotation );
558 
560  void preparedForAtlas();
561 
566  void layerStyleOverridesChanged();
567 
568  public slots:
569 
570  void refresh() override;
571 
572  void invalidateCache() override;
573 
575  void updateBoundingRect();
576 
578 
579  private slots:
580  void layersAboutToBeRemoved( const QList<QgsMapLayer *> &layers );
581 
582  void painterJobFinished();
583 
584  void shapeChanged();
585 
586  void mapThemeChanged( const QString &theme );
587 
589  void recreateCachedImageInBackground();
590 
591  private:
592 
593  QgsLayoutItemMap::MapItemFlags mMapFlags = nullptr;
594 
596  int mMapId = 1;
597 
598  std::unique_ptr< QgsLayoutItemMapGridStack > mGridStack;
599  std::unique_ptr< QgsLayoutItemMapOverviewStack > mOverviewStack;
600 
601  // Map region in map units really used for rendering
602  // It can be the same as mUserExtent, but it can be bigger in on dimension if mCalculate==Scale,
603  // so that full rectangle in paper is used.
604  QgsRectangle mExtent;
605 
608 
609  // Current temporary map region in map units. This is overwritten when atlas feature changes. It's also
610  // used when the user changes the map extent and an atlas preview is enabled. This allows the user
611  // to manually tweak each atlas preview page without affecting the actual original map extent.
612  QgsRectangle mAtlasFeatureExtent;
613 
614  // We have two images used for rendering/storing cached map images.
615  // the first (mCacheFinalImage) is used ONLY for storing the most recent completed map render. It's always
616  // used when drawing map item previews. The second (mCacheRenderingImage) is used temporarily while
617  // rendering a new preview image in the background. If (and only if) the background render completes, then
618  // mCacheRenderingImage is pushed into mCacheFinalImage, and used from then on when drawing the item preview.
619  // This ensures that something is always shown in the map item, even while refreshing the preview image in the
620  // background
621  std::unique_ptr< QImage > mCacheFinalImage;
622  std::unique_ptr< QImage > mCacheRenderingImage;
623  bool mUpdatesEnabled = true;
624 
626  bool mCacheInvalidated = true;
627 
629  int mNumCachedLayers;
630 
631  // Set to true if in state of drawing. Concurrent requests to draw method are returned if set to true
632  bool mDrawing = false;
633 
634  QTimer *mBackgroundUpdateTimer = nullptr;
635  double mPreviewScaleFactor = 0;
636 
637  bool mDrawingPreview = false;
638 
640  double mXOffset = 0.0;
642  double mYOffset = 0.0;
643 
644  double mLastRenderedImageOffsetX = 0.0;
645  double mLastRenderedImageOffsetY = 0.0;
646 
648  double mMapRotation = 0;
649 
653  double mEvaluatedMapRotation = 0;
654 
656  bool mKeepLayerSet = false;
657 
659  QList< QgsMapLayerRef > mLayers;
660 
661  bool mKeepLayerStyles = false;
663  QMap<QString, QString> mLayerStyleOverrides;
664 
666  mutable QString mCachedLayerStyleOverridesPresetName;
668  mutable QMap<QString, QString> mCachedPresetLayerStyleOverrides;
669 
674  bool mFollowVisibilityPreset = false;
675 
679  QString mFollowVisibilityPresetName;
680 
688  void drawMap( QPainter *painter, const QgsRectangle &extent, QSizeF size, double dpi );
689 
691  void connectUpdateSlot();
692 
694  void syncLayerSet();
695 
697  const QgsLayoutItemMapGrid *constFirstMapGrid() const;
698 
700  const QgsLayoutItemMapOverview *constFirstMapOverview() const;
701 
705  QTransform layoutToMapCoordsTransform() const;
706 
711  QList< QgsLabelBlockingRegion > createLabelBlockingRegions( const QgsMapSettings &mapSettings ) const;
712 
714  QRectF mCurrentRectangle;
716  bool mDrawAnnotations = true;
717 
719  bool mAtlasDriven = false;
721  AtlasScalingMode mAtlasScalingMode = Auto;
723  double mAtlasMargin = 0.10;
724 
725  std::unique_ptr< QPainter > mPainter;
726  std::unique_ptr< QgsMapRendererCustomPainterJob > mPainterJob;
727  bool mPainterCancelWait = false;
728 
729  QgsLayoutMeasurement mLabelMargin{ 0 };
730  QgsLayoutMeasurement mEvaluatedLabelMargin{ 0 };
731 
732  QStringList mBlockingLabelItemUuids;
733  QList< QPointer< QgsLayoutItem > > mBlockingLabelItems;
734 
736  QgsMapRendererJob::Errors mRenderingErrors;
737 
738  void init();
739 
741  void updateToolTip();
742 
744  QMap<QString, QString> layerStyleOverridesToRender( const QgsExpressionContext &context ) const;
745 
747  QgsRectangle transformedExtent() const;
748 
750  void mapPolygon( const QgsRectangle &extent, QPolygonF &poly ) const;
751 
757  void transformShift( double &xShift, double &yShift ) const;
758 
759  void drawAnnotations( QPainter *painter );
760  void drawAnnotation( const QgsAnnotation *item, QgsRenderContext &context );
761  QPointF layoutMapPosForItem( const QgsAnnotation *item ) const;
762 
763  void drawMapFrame( QPainter *p );
764  void drawMapBackground( QPainter *p );
765 
766  enum PartType
767  {
768  Background,
769  Layer,
770  Grid,
771  OverviewMapExtent,
772  Frame,
773  SelectionBoxes
774  };
775 
777  bool shouldDrawPart( PartType part ) const;
778 
783  void refreshMapExtents( const QgsExpressionContext *context = nullptr );
784 
785  void refreshLabelMargin( bool updateItem );
786 
787  void updateAtlasFeature();
788 
789  QgsRectangle computeAtlasRectangle();
790 
791  friend class QgsLayoutItemMapGrid;
793  friend class QgsLayoutItemLegend;
794  friend class TestQgsLayoutMap;
796 
797 };
798 
799 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsLayoutItemMap::MapItemFlags )
800 
801 #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.
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.
virtual void setFrameStrokeWidth(QgsLayoutMeasurement width)
Sets the frame stroke width.
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
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...
QgsMapRendererJob::Errors renderingErrors() const
Returns map rendering errors.
virtual int numberExportLayers() const
Returns the number of layers that this item requires for exporting during layered exports (e...
MapItemFlag
Various flags that affect drawing of map items.
#define SIP_FACTORY
Definition: qgis_sip.h:69
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
Definition: qgslayout.h:49
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.
QgsCoordinateReferenceSystem presetCrs() const
Returns the map&#39;s preset coordinate reference system.
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.
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.