QGIS API Documentation  3.17.0-Master (a035f434f4)
qgsmapcanvas.h
Go to the documentation of this file.
1 /***************************************************************************
2  qgsmapcanvas.h - description
3  -------------------
4  begin : Sun Jun 30 2002
5  copyright : (C) 2002 by Gary E.Sherman
6  email : sherman at mrcc.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 
18 #ifndef QGSMAPCANVAS_H
19 #define QGSMAPCANVAS_H
20 
21 #include "qgsconfig.h"
22 #include "qgis_sip.h"
23 
24 #include "qgsexpressioncontext.h"
25 #include "qgsrectangle.h"
26 #include "qgsfeatureid.h"
27 #include "qgsgeometry.h"
28 #include "qgscustomdrophandler.h"
29 #include "qgstemporalrangeobject.h"
31 #include "qgsproject.h"
32 
33 #include <QDomDocument>
34 #include <QGraphicsView>
35 #include <QtCore>
36 
37 #include "qgsmapsettings.h" // TEMPORARY
38 #include "qgsprevieweffect.h" //for QgsPreviewEffect::PreviewMode
39 
40 #include <QGestureEvent>
41 #include "qgis_gui.h"
42 
43 class QWheelEvent;
44 class QPixmap;
45 class QPaintEvent;
46 class QKeyEvent;
47 class ResizeEvent;
48 
49 class QColor;
50 class QDomDocument;
51 class QPaintDevice;
52 class QMouseEvent;
53 class QRubberBand;
54 class QGraphicsScene;
55 
56 class QgsMapToPixel;
57 class QgsMapLayer;
58 class QgsHighlight;
59 class QgsVectorLayer;
60 
61 class QgsLabelingResults;
64 class QgsMapSettings;
65 class QgsMapCanvasMap;
67 class QgsMapTool;
68 class QgsSnappingUtils;
69 class QgsRubberBand;
72 
74 
75 class QMenu;
76 class QgsMapMouseEvent;
77 
78 
84 class GUI_EXPORT QgsMapCanvas : public QGraphicsView
85 {
86 
87 #ifdef SIP_RUN
89  if ( qobject_cast<QgsMapCanvas *>( sipCpp ) != nullptr )
90  sipType = sipType_QgsMapCanvas;
91  else
92  sipType = nullptr;
93  SIP_END
94 #endif
95 
96  Q_OBJECT
97  Q_PROPERTY( QString theme READ theme WRITE setTheme NOTIFY themeChanged )
98  Q_PROPERTY( bool previewJobsEnabled READ previewJobsEnabled WRITE setPreviewJobsEnabled )
99 
100  public:
101 
103  QgsMapCanvas( QWidget *parent SIP_TRANSFERTHIS = nullptr );
104 
105  ~QgsMapCanvas() override;
106 
111  double magnificationFactor() const;
112 
124  void setLayers( const QList<QgsMapLayer *> &layers );
125 
126  void setCurrentLayer( QgsMapLayer *layer );
127 
132  const QgsMapSettings &mapSettings() const SIP_KEEPREFERENCE;
133 
140  void setTemporalController( QgsTemporalController *controller );
141 
148  const QgsTemporalController *temporalController() const;
149 
154  void setDestinationCrs( const QgsCoordinateReferenceSystem &crs );
155 
160  void setMapSettingsFlags( QgsMapSettings::Flags flags );
161 
166  const QgsLabelingResults *labelingResults() const;
167 
172  void setCachingEnabled( bool enabled );
173 
178  bool isCachingEnabled() const;
179 
184  void clearCache();
185 
195  void waitWhileRendering();
196 
201  void setParallelRenderingEnabled( bool enabled );
202 
207  bool isParallelRenderingEnabled() const;
208 
213  void setMapUpdateInterval( int timeMilliseconds );
214 
219  int mapUpdateInterval() const;
220 
225  double scale() const;
226 
228  double mapUnitsPerPixel() const;
229 
231  QgsRectangle extent() const;
233  QgsRectangle fullExtent() const;
234 
246  void setExtent( const QgsRectangle &r, bool magnified = false );
247 
256  bool setReferencedExtent( const QgsReferencedRectangle &extent ) SIP_THROW( QgsCsException );
257 
262  double rotation() const;
263 
268  void setRotation( double degrees );
269 
274  void setCenter( const QgsPointXY &center );
275 
280  QgsPointXY center() const;
281 
283  void zoomToFullExtent();
284 
286  void zoomToPreviousExtent();
287 
289  void zoomToNextExtent();
290 
292  void clearExtentHistory();
293 
294 
300  void zoomToFeatureIds( QgsVectorLayer *layer, const QgsFeatureIds &ids );
301 
308  void panToFeatureIds( QgsVectorLayer *layer, const QgsFeatureIds &ids, bool alwaysRecenter = true );
309 
311  void panToSelected( QgsVectorLayer *layer = nullptr );
312 
325  void flashFeatureIds( QgsVectorLayer *layer, const QgsFeatureIds &ids,
326  const QColor &startColor = QColor( 255, 0, 0, 255 ), const QColor &endColor = QColor( 255, 0, 0, 0 ),
327  int flashes = 3, int duration = 500 );
328 
341  void flashGeometries( const QList< QgsGeometry > &geometries, const QgsCoordinateReferenceSystem &crs = QgsCoordinateReferenceSystem(),
342  const QColor &startColor = QColor( 255, 0, 0, 255 ), const QColor &endColor = QColor( 255, 0, 0, 0 ),
343  int flashes = 3, int duration = 500 );
344 
346  void setMapTool( QgsMapTool *mapTool, bool clean = false );
347 
355  void unsetMapTool( QgsMapTool *mapTool );
356 
358  QgsMapTool *mapTool();
359 
365  void setProject( QgsProject *project );
366 
373  QgsProject *project();
374 
376  void setCanvasColor( const QColor &_newVal );
378  QColor canvasColor() const;
379 
384  void setSelectionColor( const QColor &color );
385 
390  QColor selectionColor() const;
391 
393  void updateScale();
394 
396  QgsMapLayer *layer( int index );
397 
399  int layerCount() const;
400 
405  QList<QgsMapLayer *> layers() const;
406 
416  void freeze( bool frozen = true );
417 
425  bool isFrozen() const;
426 
435  bool renderFlag() const { return mRenderFlag; }
436 
441  QgsUnitTypes::DistanceUnit mapUnits() const;
442 
448  QMap<QString, QString> layerStyleOverrides() const;
449 
461  void setLayerStyleOverrides( const QMap<QString, QString> &overrides );
462 
481  void setTheme( const QString &theme );
482 
488  QString theme() const { return mTheme; }
489 
491  const QgsMapToPixel *getCoordinateTransform();
492 
494  bool isDrawing();
495 
497  QgsMapLayer *currentLayer();
498 
500  void setWheelFactor( double factor );
501 
509  void zoomScale( double scale, bool ignoreScaleLock = false );
510 
518  void zoomByFactor( double scaleFactor, const QgsPointXY *center = nullptr, bool ignoreScaleLock = false );
519 
521  void zoomWithCenter( int x, int y, bool zoomIn );
522 
527  void zoomToFeatureExtent( QgsRectangle &rect );
528 
534  bool scaleLocked() const { return mScaleLocked;}
535 
537  void enableAntiAliasing( bool flag );
538 
540  bool antiAliasingEnabled() const { return mSettings.testFlag( QgsMapSettings::Antialiasing ); }
541 
543  void enableMapTileRendering( bool flag );
544 
545  // following 2 methods should be moved elsewhere or changed to private
546  // currently used by pan map tool
548  void panActionEnd( QPoint releasePoint );
549 
550 #ifndef SIP_RUN
551 
557  void panActionStart( QPoint releasePoint );
558 #endif
559 
561  void panAction( QMouseEvent *event );
562 
564  QPoint mouseLastXY();
565 
572  void setPreviewModeEnabled( bool previewEnabled );
573 
581  bool previewModeEnabled() const;
582 
592  void setPreviewMode( QgsPreviewEffect::PreviewMode mode );
593 
602  QgsPreviewEffect::PreviewMode previewMode() const;
603 
612  QgsSnappingUtils *snappingUtils() const;
613 
622  void setSnappingUtils( QgsSnappingUtils *utils );
623 
634  void setExpressionContextScope( const QgsExpressionContextScope &scope ) { mExpressionContextScope = scope; }
635 
644  QgsExpressionContextScope &expressionContextScope() { return mExpressionContextScope; }
645 
653  const QgsExpressionContextScope &expressionContextScope() const { return mExpressionContextScope; } SIP_SKIP
654 
661  QgsExpressionContextScope *defaultExpressionContextScope() SIP_FACTORY;
662 
667  void setSegmentationTolerance( double tolerance );
668 
673  void setSegmentationToleranceType( QgsAbstractGeometry::SegmentationToleranceType type );
674 
679  QList< QgsMapCanvasAnnotationItem *> annotationItems() const;
680 
686  bool annotationsVisible() const { return mAnnotationsVisible; }
687 
693  void setAnnotationsVisible( bool visible );
694 
699  void setLabelingEngineSettings( const QgsLabelingEngineSettings &settings );
700 
705  const QgsLabelingEngineSettings &labelingEngineSettings() const;
706 
715  bool previewJobsEnabled() const;
716 
725  void setPreviewJobsEnabled( bool enabled );
726 
732  void setCustomDropHandlers( const QVector<QPointer<QgsCustomDropHandler >> &handlers ) SIP_SKIP;
733 
744  void setTemporalRange( const QgsDateTimeRange &range );
745 
752  const QgsDateTimeRange &temporalRange() const;
753 
765  void installInteractionBlocker( QgsMapCanvasInteractionBlocker *blocker );
766 
774  void removeInteractionBlocker( QgsMapCanvasInteractionBlocker *blocker );
775 
781  bool allowInteraction( QgsMapCanvasInteractionBlocker::Interaction interaction ) const;
782 
783  public slots:
784 
786  void refresh();
787 
797  void refreshAllLayers();
798 
807  void redrawAllLayers();
808 
810  void selectionChangedSlot();
811 
813  void saveAsImage( const QString &fileName, QPixmap *QPixmap = nullptr, const QString & = "PNG" );
814 
816  void layerStateChange();
817 
825  void setRenderFlag( bool flag );
826 
831  void stopRendering();
832 
834  void readProject( const QDomDocument & );
835 
837  void writeProject( QDomDocument & );
838 
847  void setMagnificationFactor( double factor, const QgsPointXY *center = nullptr );
848 
854  void setScaleLocked( bool isLocked );
855 
857  void zoomIn();
858 
860  void zoomOut();
861 
866  void zoomToSelected( QgsVectorLayer *layer = nullptr );
867 
873  void setZoomResolutions( const QList<double> &resolutions ) { mZoomResolutions = resolutions; }
874 
880  const QList<double> &zoomResolutions() const { return mZoomResolutions; }
881 
882  private slots:
884  void mapToolDestroyed();
885 
887  void rendererJobFinished();
888 
890  void previewJobFinished();
891 
892  void mapUpdateTimeout();
893 
894  void refreshMap();
895 
896  void mapThemeChanged( const QString &theme );
898  void mapThemeRenamed( const QString &theme, const QString &newTheme );
899 
900  signals:
901 
906  void xyCoordinates( const QgsPointXY &p );
907 
909  void scaleChanged( double );
910 
912  void extentsChanged();
913 
918  void rotationChanged( double );
919 
924  void magnificationChanged( double );
925 
930  void canvasColorChanged();
931 
932  // TODO: deprecate when decorations are reimplemented as map canvas items
933 
944  void renderComplete( QPainter * );
945 
946  // ### QGIS 3: renamte to mapRefreshFinished()
948  void mapCanvasRefreshed();
949 
950  // ### QGIS 3: rename to mapRefreshStarted()
952  void renderStarting();
953 
955  void layersChanged();
956 
958  void keyPressed( QKeyEvent *e );
959 
961  void keyReleased( QKeyEvent *e );
962 
967  void mapToolSet( QgsMapTool *newTool, QgsMapTool *oldTool );
968 
969 
971  void selectionChanged( QgsVectorLayer *layer );
972 
974  void zoomLastStatusChanged( bool );
975 
977  void zoomNextStatusChanged( bool );
978 
983  void destinationCrsChanged();
984 
989  void transformContextChanged();
990 
995  void currentLayerChanged( QgsMapLayer *layer );
996 
1001  void layerStyleOverridesChanged();
1002 
1008  void themeChanged( const QString &theme );
1009 
1011  void messageEmitted( const QString &title, const QString &message, Qgis::MessageLevel = Qgis::Info );
1012 
1020  void renderErrorOccurred( const QString &error, QgsMapLayer *layer );
1021 
1032  void panDistanceBearingChanged( double distance, QgsUnitTypes::DistanceUnit unit, double bearing );
1033 
1038  void tapAndHoldGestureOccurred( const QgsPointXY &mapPoint, QTapAndHoldGesture *gesture );
1039 
1045  void temporalRangeChanged();
1046 
1047 
1054  void contextMenuAboutToShow( QMenu *menu, QgsMapMouseEvent *event );
1055 
1056 
1057  protected:
1058 
1059  bool event( QEvent *e ) override;
1060  void keyPressEvent( QKeyEvent *e ) override;
1061  void keyReleaseEvent( QKeyEvent *e ) override;
1062  void mouseDoubleClickEvent( QMouseEvent *e ) override;
1063  void mouseMoveEvent( QMouseEvent *e ) override;
1064  void mousePressEvent( QMouseEvent *e ) override;
1065  void mouseReleaseEvent( QMouseEvent *e ) override;
1066  void wheelEvent( QWheelEvent *e ) override;
1067  void resizeEvent( QResizeEvent *e ) override;
1068  void paintEvent( QPaintEvent *e ) override;
1069  void dragEnterEvent( QDragEnterEvent *e ) override;
1070 
1072  void moveCanvasContents( bool reset = false );
1073 
1074  void dropEvent( QDropEvent *event ) override;
1075 
1076 
1079 
1081  std::unique_ptr<CanvasProperties> mCanvasProperties;
1082 
1083 #if 0
1084 
1089  void connectNotify( const char *signal ) override;
1090 #endif
1091 
1092  protected slots:
1094  void updateCanvasItemPositions();
1095 
1096  private slots:
1097 
1098  void layerRepaintRequested( bool deferred );
1099 
1100  void autoRefreshTriggered();
1101 
1102  void updateAutoRefreshTimer();
1103 
1104  void projectThemesChanged();
1105 
1106  void startPreviewJob( int number );
1107 
1108  private:
1109 
1110  // Restore scale RAII
1111  class ScaleRestorer
1112  {
1113  public:
1114  ScaleRestorer( QgsMapCanvas *canvas ):
1115  mCanvas( canvas )
1116  {
1117  mLockedScale = mCanvas->mapSettings().scale();
1118  };
1119 
1120  ~ScaleRestorer()
1121  {
1122  QgsRectangle newExtent = mCanvas->mapSettings().extent();
1123  newExtent.scale( mLockedScale / mCanvas->mapSettings().scale() );
1124  mCanvas->mSettings.setExtent( newExtent );
1125  };
1126 
1127  private:
1128  QgsMapCanvas *mCanvas;
1129  double mLockedScale;
1130  };
1131 
1133  QgsMapSettings mSettings;
1134 
1136  QgsMapCanvasMap *mMap = nullptr;
1137 
1142  QgsTemporalController *mController = nullptr;
1143 
1145  bool mFrozen = false;
1146 
1148  bool mRefreshScheduled = false;
1149 
1151  bool mRefreshAfterJob = false;
1152 
1154  bool mRenderFlag = true;
1155 
1157  QPointer< QgsMapLayer > mCurrentLayer;
1158 
1160  QGraphicsScene *mScene = nullptr;
1161 
1163  QgsMapTool *mMapTool = nullptr;
1164 
1166  QgsMapTool *mLastNonZoomMapTool = nullptr;
1167 
1169  QgsProject *mProject = nullptr;
1170 
1172  QMenu *mMenu = nullptr;
1173 
1175  QList <QgsRectangle> mLastExtent;
1176  int mLastExtentIndex = -1;
1177 
1179  double mWheelZoomFactor = 2.0;
1180 
1182  QTimer mMapUpdateTimer;
1183 
1185  QgsMapRendererQImageJob *mJob = nullptr;
1186 
1188  bool mJobCanceled = false;
1189 
1191  QgsLabelingResults *mLabelingResults = nullptr;
1192 
1194  bool mUseParallelRendering = false;
1195 
1197  bool mDrawRenderingStats = false;
1198 
1200  QgsMapRendererCache *mCache = nullptr;
1201 
1202  QTimer *mResizeTimer = nullptr;
1203  QTimer *mRefreshTimer = nullptr;
1204 
1205  QgsPreviewEffect *mPreviewEffect = nullptr;
1206 
1207  QgsRectangle imageRect( const QImage &img, const QgsMapSettings &mapSettings );
1208 
1209  QgsSnappingUtils *mSnappingUtils = nullptr;
1210 
1211  QList< QgsMapRendererQImageJob * > mPreviewJobs;
1212 
1214  bool mScaleLocked = false;
1215 
1216  QgsExpressionContextScope mExpressionContextScope;
1217 
1219  QRect mZoomRect;
1220 
1222  bool mZoomDragging = false;
1223 
1225  std::unique_ptr< QgsRubberBand > mZoomRubberBand;
1226 
1227  QCursor mZoomCursor;
1228 
1229  QTimer mAutoRefreshTimer;
1230 
1231  QTimer mPreviewTimer;
1232  QMetaObject::Connection mPreviewTimerConnection;
1233 
1234  QString mTheme;
1235 
1236  QgsPointXY mCursorPoint;
1237 
1238  bool mAnnotationsVisible = true;
1239 
1240  bool mUsePreviewJobs = false;
1241 
1242  QHash< QString, int > mLastLayerRenderTime;
1243 
1244  QVector<QPointer<QgsCustomDropHandler >> mDropHandlers;
1245 
1246  QgsDistanceArea mDa;
1247  QList<double> mZoomResolutions;
1248 
1249  QList< QgsMapCanvasInteractionBlocker * > mInteractionBlockers;
1250 
1255  QgsPointXY cursorPoint() const;
1256 
1261  void updateMapSize();
1262 
1268  void beginZoomRect( QPoint pos );
1269 
1275  void endZoomRect( QPoint pos );
1276 
1285  bool boundingBoxOfFeatureIds( const QgsFeatureIds &ids, QgsVectorLayer *layer, QgsRectangle &bbox, QString &errorMsg ) const;
1286 
1293  QgsRectangle optimalExtentForPointLayer( QgsVectorLayer *layer, const QgsPointXY &center, int scaleFactor = 5 );
1294 
1295  void setLayersPrivate( const QList<QgsMapLayer *> &layers );
1296 
1297  void startPreviewJobs();
1298  void stopPreviewJobs();
1299  void schedulePreviewJob( int number );
1300 
1304  bool panOperationInProgress();
1305 
1306  int nextZoomLevel( const QList<double> &resolutions, bool zoomIn = true ) const;
1307  double zoomInFactor() const;
1308  double zoomOutFactor() const;
1309 
1314  void clearTemporalCache();
1315 
1316  void showContextMenu( QgsMapMouseEvent *event );
1317 
1318  friend class TestQgsMapCanvas;
1319 
1320 }; // class QgsMapCanvas
1321 
1322 // clazy:excludeall=qstring-allocations
1323 
1324 #endif
A rectangle specified with double values.
Definition: qgsrectangle.h:41
Base class for all map layer types.
Definition: qgsmaplayer.h:83
std::unique_ptr< CanvasProperties > mCanvasProperties
Handle pattern for implementation object.
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:37
const QList< double > & zoomResolutions() const
Definition: qgsmapcanvas.h:880
Interaction
Available interactions to block.
#define SIP_TRANSFERTHIS
Definition: qgis_sip.h:53
A widget that displays an overview map.
bool annotationsVisible() const
Returns true if annotations are visible within the map canvas.
Definition: qgsmapcanvas.h:686
A class to represent a 2D point.
Definition: qgspointxy.h:43
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
Definition: qgsrectangle.h:235
A QgsMapMouseEvent is the result of a user interaction with the mouse on a QgsMapCanvas.
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:123
SegmentationToleranceType
Segmentation tolerance as maximum angle or maximum difference between approximation and circle...
const QgsCoordinateReferenceSystem & crs
MessageLevel
Level for messages This will be used both for message log and message bar in application.
Definition: qgis.h:88
Map canvas is a class for displaying all GIS data types on a canvas.
Definition: qgsmapcanvas.h:84
A graphics effect which can be applied to a widget to simulate various printing and color blindness m...
The QgsMapSettings class contains configuration for rendering of the map.
Deprecated to be deleted, stuff from here should be moved elsewhere.
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:37
#define SIP_SKIP
Definition: qgis_sip.h:126
A class for drawing transient features (e.g.
Definition: qgsrubberband.h:49
Enable anti-aliasing for map rendering.
A class for highlight features on the map.
Definition: qgshighlight.h:57
#define SIP_END
Definition: qgis_sip.h:194
Encapsulates a QGIS project, including sets of map layers and their styles, layouts, annotations, canvases, etc.
Definition: qgsproject.h:94
#define SIP_KEEPREFERENCE
Definition: qgis_sip.h:86
void setZoomResolutions(const QList< double > &resolutions)
Set a list of resolutions (map units per pixel) to which to "snap to" when zooming the map...
Definition: qgsmapcanvas.h:873
A QgsRectangle with associated coordinate reference system.
#define SIP_FACTORY
Definition: qgis_sip.h:76
Single scope for storing variables and functions for use within a QgsExpressionContext.
void setExpressionContextScope(const QgsExpressionContextScope &scope)
Sets an expression context scope for the map canvas.
Definition: qgsmapcanvas.h:634
A controller base class for temporal objects, contains a signal for notifying updates of the objects ...
DistanceUnit
Units of distance.
Definition: qgsunittypes.h:67
Abstract base class for all map tools.
Definition: qgsmaptool.h:63
A general purpose distance and area calculator, capable of performing ellipsoid based calculations...
QString theme() const
Returns the map&#39;s theme shown in the canvas, if set.
Definition: qgsmapcanvas.h:488
QgsExpressionContextScope & expressionContextScope()
Returns a reference to the expression context scope for the map canvas.
Definition: qgsmapcanvas.h:644
An interface for objects which block interactions with a QgsMapCanvas.
bool antiAliasingEnabled() const
true if antialiasing is enabled
Definition: qgsmapcanvas.h:540
bool scaleLocked() const
Returns whether the scale is locked, so zooming can be performed using magnication.
Definition: qgsmapcanvas.h:534
const QgsExpressionContextScope & expressionContextScope() const
Returns a const reference to the expression context scope for the map canvas.
Definition: qgsmapcanvas.h:653
Intermediate base class adding functionality that allows client to query the rendered image...
Stores global configuration for labeling engine.
This class represents a coordinate reference system (CRS).
This class has all the configuration of snapping and can return answers to snapping queries...
#define SIP_CONVERT_TO_SUBCLASS_CODE(code)
Definition: qgis_sip.h:177
#define SIP_THROW(name)
Definition: qgis_sip.h:189
Class that stores computed placement from labeling engine.
This class is responsible for keeping cache of rendered images resulting from a map rendering job...
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:65
Represents a vector layer which manages a vector based data sets.
An interactive map canvas item which displays a QgsAnnotation.