QGIS API Documentation 4.1.0-Master (3b8ef1f72a3)
Loading...
Searching...
No Matches
qgsmapcanvas.cpp
Go to the documentation of this file.
1/***************************************************************************
2qgsmapcanvas.cpp - description
3------------------ -
4begin : Sun Jun 30 2002
5copyright : (C) 2002 by Gary E.Sherman
6email : 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#include "qgsmapcanvas.h"
19
20#include <cmath>
21#include <memory>
22
23#include "qgis.h"
24#include "qgs2dmapcontroller.h"
25#include "qgsannotationlayer.h"
26#include "qgsapplication.h"
31#include "qgsexception.h"
33#include "qgsfeatureiterator.h"
34#include "qgsgrouplayer.h"
35#include "qgsimagecache.h"
36#include "qgslabelingresults.h"
37#include "qgslogger.h"
39#include "qgsmapcanvasmap.h"
41#include "qgsmaplayer.h"
44#include "qgsmaplayerutils.h"
45#include "qgsmapmouseevent.h"
46#include "qgsmaprenderercache.h"
48#include "qgsmaprendererjob.h"
51#include "qgsmapsettingsutils.h"
53#include "qgsmaptoolpan.h"
54#include "qgsmaptopixel.h"
55#include "qgsmessagelog.h"
56#include "qgsmimedatautils.h"
58#include "qgsproject.h"
63#include "qgsrubberband.h"
64#include "qgsruntimeprofiler.h"
65#include "qgsscreenhelper.h"
66#include "qgssettings.h"
70#include "qgssettingstree.h"
71#include "qgsstatusbar.h"
72#include "qgssvgcache.h"
73#include "qgssymbollayerutils.h"
76#include "qgsvectorlayer.h"
77#include "qgsvectortilelayer.h"
78
79#include <QApplication>
80#include <QClipboard>
81#include <QCursor>
82#include <QDir>
83#include <QFile>
84#include <QGraphicsItem>
85#include <QGraphicsScene>
86#include <QGraphicsView>
87#include <QKeyEvent>
88#include <QMenu>
89#include <QPaintEvent>
90#include <QPainter>
91#include <QPixmap>
92#include <QPropertyAnimation>
93#include <QRect>
94#include <QResizeEvent>
95#include <QScreen>
96#include <QString>
97#include <QStringList>
98#include <QTextStream>
99#include <QVariantAnimation>
100#include <QWheelEvent>
101#include <QWindow>
102#include <QtGlobal>
103
104#include "moc_qgsmapcanvas.cpp"
105
106using namespace Qt::StringLiterals;
107
109
115//TODO QGIS 5.0 - remove
117{
118 public:
122 CanvasProperties() = default;
123
125 bool mouseButtonDown { false };
126
129
132
134 bool panSelectorDown { false };
135};
136
137
139 : QGraphicsView( parent )
141 , mExpressionContextScope( tr( "Map Canvas" ) )
142{
143 mScene = new QGraphicsScene();
144 mLayout = new QgsOverlayWidgetLayout();
145 setLayout( mLayout );
146
147 setScene( mScene );
148 setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
149 setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
150 setMouseTracking( true );
151 setFocusPolicy( Qt::StrongFocus );
152
153 mScreenHelper = new QgsScreenHelper( this );
154 connect( mScreenHelper, &QgsScreenHelper::screenDpiChanged, this, &QgsMapCanvas::updateDevicePixelFromScreen );
155
156 mResizeTimer = new QTimer( this );
157 mResizeTimer->setSingleShot( true );
158 connect( mResizeTimer, &QTimer::timeout, this, &QgsMapCanvas::refresh );
159
160 mRefreshTimer = new QTimer( this );
161 mRefreshTimer->setSingleShot( true );
162 connect( mRefreshTimer, &QTimer::timeout, this, &QgsMapCanvas::refreshMap );
163
164 // create map canvas item which will show the map
165 mMap = new QgsMapCanvasMap( this );
166
167 // project handling
170
171 connect( QgsProject::instance()->mainAnnotationLayer(), &QgsMapLayer::repaintRequested, this, &QgsMapCanvas::layerRepaintRequested );
172 connect( QgsProject::instance()->mapThemeCollection(), &QgsMapThemeCollection::mapThemeChanged, this, &QgsMapCanvas::mapThemeChanged );
173 connect( QgsProject::instance()->mapThemeCollection(), &QgsMapThemeCollection::mapThemeRenamed, this, &QgsMapCanvas::mapThemeRenamed );
174 connect( QgsProject::instance()->mapThemeCollection(), &QgsMapThemeCollection::mapThemesChanged, this, &QgsMapCanvas::projectThemesChanged );
175
176 {
177 QgsScopedRuntimeProfile profile( "Map settings initialization" );
178 mSettings.setFlag( Qgis::MapSettingsFlag::DrawEditingInfo );
181 mSettings.setEllipsoid( QgsProject::instance()->ellipsoid() );
182 connect( QgsProject::instance(), &QgsProject::ellipsoidChanged, this, [this] {
183 mSettings.setEllipsoid( QgsProject::instance()->ellipsoid() );
184 refresh();
185 } );
186 mSettings.setTransformContext( QgsProject::instance()->transformContext() );
188 mSettings.setTransformContext( QgsProject::instance()->transformContext() );
190 refresh();
191 } );
192
193 mSettings.setScaleMethod( QgsProject::instance()->scaleMethod() );
194 connect( QgsProject::instance(), &QgsProject::scaleMethodChanged, this, [this] {
195 mSettings.setScaleMethod( QgsProject::instance()->scaleMethod() );
196 updateScale();
197 refresh();
198 } );
199
201 QgsCoordinateReferenceSystem crs = mSettings.destinationCrs();
202 crs.updateDefinition();
203 if ( mSettings.destinationCrs() != crs )
204 {
205 // user crs has changed definition, refresh the map
206 setDestinationCrs( crs );
207 }
208 } );
209 }
210
211 // refresh canvas when a remote svg/image has finished downloading
214 // refresh canvas when project color scheme is changed -- if layers use project colors, they need to be redrawn
216
217 //segmentation parameters
218 mSettings.setSegmentationTolerance( QgsSettingsRegistryGui::settingsSegmentationTolerance->value() );
219 mSettings.setSegmentationToleranceType( QgsSettingsRegistryGui::settingsSegmentationToleranceType->value() );
220
221 mWheelZoomFactor = QgsSettingsRegistryGui::settingsZoomFactor->value();
222
223 QSize s = viewport()->size();
224 mSettings.setOutputSize( s );
225
226 mSettings.setRendererUsage( Qgis::RendererUsage::View );
227
228 setSceneRect( 0, 0, s.width(), s.height() );
229 mScene->setSceneRect( QRectF( 0, 0, s.width(), s.height() ) );
230
231 moveCanvasContents( true );
232
233 connect( &mMapUpdateTimer, &QTimer::timeout, this, &QgsMapCanvas::mapUpdateTimeout );
234 mMapUpdateTimer.setInterval( 250 );
235
236#ifdef Q_OS_WIN
237 // Enable touch event on Windows.
238 // Qt on Windows needs to be told it can take touch events or else it ignores them.
239 grabGesture( Qt::PinchGesture );
240 grabGesture( Qt::TapAndHoldGesture );
241 viewport()->setAttribute( Qt::WA_AcceptTouchEvents );
242#endif
243
244 mPreviewEffect = new QgsPreviewEffect( this );
245 viewport()->setGraphicsEffect( mPreviewEffect );
246
248
249 connect( &mAutoRefreshTimer, &QTimer::timeout, this, &QgsMapCanvas::autoRefreshTriggered );
250
252
253 setInteractive( false );
254
255 // make sure we have the same default in QgsMapSettings and the scene's background brush
256 // (by default map settings has white bg color, scene background brush is black)
257 setCanvasColor( mSettings.backgroundColor() );
258
259 setTemporalRange( mSettings.temporalRange() );
260 refresh();
261}
262
263
265{
266 if ( mMapTool )
267 {
268 mMapTool->deactivate();
269 disconnect( mMapTool, &QObject::destroyed, this, &QgsMapCanvas::mapToolDestroyed );
270 mMapTool = nullptr;
271 }
272
273 // we also clear the canvas pointer for all child map tools. We're now in a partially destroyed state and it's
274 // no longer safe for map tools to try to cleanup things in the canvas during their destruction (such as removing
275 // associated canvas items)
276 // NOTE -- it may be better to just delete the map tool children here upfront?
277 const QList<QgsMapTool *> tools = findChildren<QgsMapTool *>();
278 for ( QgsMapTool *tool : tools )
279 {
280 tool->mCanvas = nullptr;
281 }
282
283 cancelJobs();
284
285 // delete canvas items prior to deleting the canvas
286 // because they might try to update canvas when it's
287 // already being destructed, ends with segfault
288 qDeleteAll( mScene->items() );
289
290 mScene->deleteLater(); // crashes in python tests on windows
291}
292
293void QgsMapCanvas::addOverlayWidget( QWidget *widget, Qt::Edge edge )
294{
295 mLayout->addWidget( widget, edge );
296}
297
299{
300 // rendering job may still end up writing into canvas map item
301 // so kill it before deleting canvas items
302 if ( mJob )
303 {
304 whileBlocking( mJob )->cancel();
305 delete mJob;
306 mJob = nullptr;
307 }
308
309 for ( auto previewJob = mPreviewJobs.constBegin(); previewJob != mPreviewJobs.constEnd(); ++previewJob )
310 {
311 if ( *previewJob )
312 {
313 whileBlocking( *previewJob )->cancel();
314 delete *previewJob;
315 }
316 }
317 mPreviewJobs.clear();
318}
319
321{
322 // do not go higher or lower than min max magnification ratio
323 double magnifierMin = QgsGuiUtils::CANVAS_MAGNIFICATION_MIN;
324 double magnifierMax = QgsGuiUtils::CANVAS_MAGNIFICATION_MAX;
325 factor = std::clamp( factor, magnifierMin, magnifierMax );
326
327 // the magnifier widget is in integer percent
328 if ( !qgsDoubleNear( factor, mSettings.magnificationFactor(), 0.01 ) )
329 {
330 mSettings.setMagnificationFactor( factor, center );
331 refresh();
332 emit magnificationChanged( factor );
333 }
334}
335
337{
338 return mSettings.magnificationFactor();
339}
340
342{
343 mSettings.setFlag( Qgis::MapSettingsFlag::Antialiasing, flag );
344 mSettings.setFlag( Qgis::MapSettingsFlag::HighQualityImageTransforms, flag );
345}
346
348{
349 return mSettings.testFlag( Qgis::MapSettingsFlag::Antialiasing );
350}
351
353{
354 mSettings.setFlag( Qgis::MapSettingsFlag::RenderMapTile, flag );
355}
356
358{
359 QList<QgsMapLayer *> layers = mapSettings().layers();
360 if ( index >= 0 && index < layers.size() )
361 return layers[index];
362 else
363 return nullptr;
364}
365
366QgsMapLayer *QgsMapCanvas::layer( const QString &id )
367{
368 // first check for layers from canvas map settings
369 const QList<QgsMapLayer *> layers = mapSettings().layers();
370 for ( QgsMapLayer *layer : layers )
371 {
372 if ( layer && layer->id() == id )
373 return layer;
374 }
375
376 // else fallback to searching project layers
377 // TODO: allow a specific project to be associated with a canvas!
378 return QgsProject::instance()->mapLayer( id );
379}
380
382{
383 if ( mCurrentLayer == layer )
384 return;
385
386 mCurrentLayer = layer;
388}
389
391{
392 return mapSettings().scale();
393}
394
396{
397 return nullptr != mJob;
398} // isDrawing
399
400// return the current coordinate transform based on the extents and
401// device size
406
407void QgsMapCanvas::setLayers( const QList<QgsMapLayer *> &layers )
408{
409 // following a theme => request denied!
410 if ( !mTheme.isEmpty() )
411 return;
412
413 setLayersPrivate( layers );
414}
415
420
422{
423 return mFlags;
424}
425
426void QgsMapCanvas::setLayersPrivate( const QList<QgsMapLayer *> &layers )
427{
428 const QList<QgsMapLayer *> oldLayers = mSettings.layers();
429
430 // update only if needed
431 if ( layers == oldLayers )
432 return;
433
434 for ( QgsMapLayer *layer : oldLayers )
435 {
436 disconnect( layer, &QgsMapLayer::repaintRequested, this, &QgsMapCanvas::layerRepaintRequested );
437 disconnect( layer, &QgsMapLayer::autoRefreshIntervalChanged, this, &QgsMapCanvas::updateAutoRefreshTimer );
438 switch ( layer->type() )
439 {
441 {
442 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
444 disconnect( vlayer, &QgsVectorLayer::rendererChanged, this, &QgsMapCanvas::updateAutoRefreshTimer );
445 break;
446 }
447
449 {
450 QgsVectorTileLayer *vtlayer = qobject_cast<QgsVectorTileLayer *>( layer );
452 break;
453 }
454
462 break;
463 }
464 }
465
466 mSettings.setLayers( layers );
467
468 for ( QgsMapLayer *layer : std::as_const( layers ) )
469 {
470 if ( !layer )
471 continue;
472 connect( layer, &QgsMapLayer::repaintRequested, this, &QgsMapCanvas::layerRepaintRequested );
473 connect( layer, &QgsMapLayer::autoRefreshIntervalChanged, this, &QgsMapCanvas::updateAutoRefreshTimer );
474
475 switch ( layer->type() )
476 {
478 {
479 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
481 connect( vlayer, &QgsVectorLayer::rendererChanged, this, &QgsMapCanvas::updateAutoRefreshTimer );
482 break;
483 }
484
486 {
487 QgsVectorTileLayer *vtlayer = qobject_cast<QgsVectorTileLayer *>( layer );
489 break;
490 }
491
499 break;
500 }
501 }
502
503 QgsDebugMsgLevel( u"Layers have changed, refreshing"_s, 2 );
504 emit layersChanged();
505
506 updateAutoRefreshTimer();
507 refresh();
508}
509
510
512{
513 return mSettings;
514}
515
517{
518 return mSettings;
519}
520
522{
523 if ( mSettings.destinationCrs() == crs )
524 return;
525
526 // try to reproject current extent to the new one
527 QgsRectangle rect;
528 if ( !mSettings.visibleExtent().isEmpty() )
529 {
532 try
533 {
534 rect = transform.transformBoundingBox( mSettings.visibleExtent() );
535 }
536 catch ( QgsCsException &e )
537 {
538 Q_UNUSED( e )
539 QgsDebugError( u"Transform error caught: %1"_s.arg( e.what() ) );
540 }
541 }
542
543 // defer extent and scale changed signals until we've correctly
544 // set the destination crs, otherwise slots which connect to these signals
545 // may retrieve an outdated CRS for the map canvas
546 mBlockExtentChangedSignal++;
547 mBlockScaleChangedSignal++;
548
549 if ( !rect.isEmpty() )
550 {
551 // we will be manually calling updateCanvasItemPositions() later, AFTER setting the updating the mSettings destination CRS, and we don't
552 // want to do that twice!
553 mBlockItemPositionUpdates++;
554 setExtent( rect );
555 mBlockItemPositionUpdates--;
556 }
557
558 mBlockExtentChangedSignal--;
559 mBlockScaleChangedSignal--;
560
561 mSettings.setDestinationCrs( crs );
562 updateScale();
564
566
567 QgsDebugMsgLevel( u"refreshing after destination CRS changed"_s, 2 );
568 refresh();
569
571}
572
574{
575 if ( mController )
577 if ( QgsTemporalNavigationObject *temporalNavigationObject = qobject_cast<QgsTemporalNavigationObject *>( mController ) )
578 {
579 disconnect( temporalNavigationObject, &QgsTemporalNavigationObject::navigationModeChanged, this, &QgsMapCanvas::temporalControllerModeChanged );
580
581 // clear any existing animation settings from map settings. We don't do this on every render, as a 3rd party plugin
582 // might be in control of these!
583 mSettings.setFrameRate( -1 );
584 mSettings.setCurrentFrame( -1 );
585 }
586
587 mController = controller;
589 if ( QgsTemporalNavigationObject *temporalNavigationObject = qobject_cast<QgsTemporalNavigationObject *>( mController ) )
590 connect( temporalNavigationObject, &QgsTemporalNavigationObject::navigationModeChanged, this, &QgsMapCanvas::temporalControllerModeChanged );
591}
592
593void QgsMapCanvas::temporalControllerModeChanged()
594{
595 if ( QgsTemporalNavigationObject *temporalNavigationObject = qobject_cast<QgsTemporalNavigationObject *>( mController ) )
596 {
597 switch ( temporalNavigationObject->navigationMode() )
598 {
601 mSettings.setFrameRate( temporalNavigationObject->framesPerSecond() );
602 mSettings.setCurrentFrame( temporalNavigationObject->currentFrameNumber() );
603 break;
604
607 // clear any existing animation settings from map settings. We don't do this on every render, as a 3rd party plugin
608 // might be in control of these!
609 mSettings.setFrameRate( -1 );
610 mSettings.setCurrentFrame( -1 );
611 break;
612 }
613 }
614}
615
617{
618 return mController;
619}
620
622{
623 mSettings.setFlags( flags );
624 clearCache();
625 refresh();
626}
627
628const QgsLabelingResults *QgsMapCanvas::labelingResults( bool allowOutdatedResults ) const
629{
630 if ( !allowOutdatedResults && mLabelingResultsOutdated )
631 return nullptr;
632
633 return mLabelingResults.get();
634}
635
636const QgsRenderedItemResults *QgsMapCanvas::renderedItemResults( bool allowOutdatedResults ) const
637{
638 if ( !allowOutdatedResults && mRenderedItemResultsOutdated )
639 return nullptr;
640
641 return mRenderedItemResults.get();
642}
643
645{
646 if ( enabled == isCachingEnabled() )
647 return;
648
649 if ( mJob && mJob->isActive() )
650 {
651 // wait for the current rendering to finish, before touching the cache
652 mJob->waitForFinished();
653 }
654
655 if ( enabled )
656 {
657 mCache = std::make_unique<QgsMapRendererCache>();
658 }
659 else
660 {
661 mCache.reset();
662 }
663 mPreviousRenderedItemResults.reset();
664}
665
667{
668 return nullptr != mCache.get();
669}
670
672{
673 if ( mCache )
674 mCache->clear();
675
676 if ( mPreviousRenderedItemResults )
677 mPreviousRenderedItemResults.reset();
678 if ( mRenderedItemResults )
679 mRenderedItemResults.reset();
680}
681
683{
684 return mCache.get();
685}
686
688{
689 mUseParallelRendering = enabled;
690}
691
693{
694 return mUseParallelRendering;
695}
696
697void QgsMapCanvas::setMapUpdateInterval( int timeMilliseconds )
698{
699 mMapUpdateTimer.setInterval( timeMilliseconds );
700}
701
703{
704 return mMapUpdateTimer.interval();
705}
706
707
709{
710 return mCurrentLayer;
711}
712
714{
715 QgsExpressionContextScope *s = new QgsExpressionContextScope( QObject::tr( "Map Canvas" ) );
716 s->setVariable( u"canvas_cursor_point"_s, QgsGeometry::fromPointXY( cursorPoint() ), true );
717 return s;
718}
719
721{
722 //build the expression context
723 QgsExpressionContext expressionContext;
724 expressionContext
729 if ( QgsExpressionContextScopeGenerator *generator = dynamic_cast<QgsExpressionContextScopeGenerator *>( mController ) )
730 {
731 expressionContext << generator->createExpressionContextScope();
732 }
733 expressionContext << defaultExpressionContextScope() << new QgsExpressionContextScope( mExpressionContextScope );
734 return expressionContext;
735}
736
738{
739 if ( !mSettings.hasValidSettings() )
740 {
741 QgsDebugMsgLevel( u"CANVAS refresh - invalid settings -> nothing to do"_s, 2 );
742 return;
743 }
744
745 if ( !mRenderFlag || mFrozen )
746 {
747 QgsDebugMsgLevel( u"CANVAS render flag off"_s, 2 );
748 return;
749 }
750
751 if ( mRefreshScheduled )
752 {
753 QgsDebugMsgLevel( u"CANVAS refresh already scheduled"_s, 2 );
754 return;
755 }
756
757 mRefreshScheduled = true;
758
759 QgsDebugMsgLevel( u"CANVAS refresh scheduling"_s, 2 );
760
761 // schedule a refresh
762 mRefreshTimer->start( 1 );
763
764 mLabelingResultsOutdated = true;
765 mRenderedItemResultsOutdated = true;
766}
767
768QList<QgsMapLayer *> filterLayersForRender( const QList<QgsMapLayer *> &layers )
769{
770 QList<QgsMapLayer *> filteredLayers;
771 for ( QgsMapLayer *layer : layers )
772 {
773 if ( QgsAnnotationLayer *annotationLayer = qobject_cast<QgsAnnotationLayer *>( layer ) )
774 {
775 if ( QgsMapLayer *linkedLayer = annotationLayer->linkedVisibilityLayer() )
776 {
777 if ( !layers.contains( linkedLayer ) )
778 continue;
779 }
780 }
781 filteredLayers.append( layer );
782 }
783
784 // remove any invalid layers
785 filteredLayers.erase( std::remove_if( filteredLayers.begin(), filteredLayers.end(), []( QgsMapLayer *layer ) { return !layer || !layer->isValid(); } ), filteredLayers.end() );
786
787 return filteredLayers;
788}
789
790void QgsMapCanvas::refreshMap()
791{
792 Q_ASSERT( mRefreshScheduled );
793
794 QgsDebugMsgLevel( u"CANVAS refresh!"_s, 3 );
795
796 stopRendering(); // if any...
797 stopPreviewJobs();
798
799 if ( mCacheInvalidations.testFlag( CacheInvalidationType::Temporal ) )
800 {
801 clearTemporalCache();
802 mCacheInvalidations &= ~( static_cast<int>( CacheInvalidationType::Temporal ) );
803 }
804 if ( mCacheInvalidations.testFlag( CacheInvalidationType::Elevation ) )
805 {
806 clearElevationCache();
807 mCacheInvalidations &= ~( static_cast<int>( CacheInvalidationType::Elevation ) );
808 }
809
810 mSettings.setExpressionContext( createExpressionContext() );
811
812 // if using the temporal controller in animation mode, get the frame settings from that
813 if ( QgsTemporalNavigationObject *temporalNavigationObject = dynamic_cast<QgsTemporalNavigationObject *>( mController ) )
814 {
815 switch ( temporalNavigationObject->navigationMode() )
816 {
819 mSettings.setFrameRate( temporalNavigationObject->framesPerSecond() );
820 mSettings.setCurrentFrame( temporalNavigationObject->currentFrameNumber() );
821 break;
822
825 break;
826 }
827 }
828
829 mSettings.setPathResolver( QgsProject::instance()->pathResolver() );
830
831 if ( !mTheme.isEmpty() )
832 {
833 // IMPORTANT: we MUST set the layer style overrides here! (At the time of writing this
834 // comment) retrieving layer styles from the theme collection gives an XML snapshot of the
835 // current state of the style. If we had stored the style overrides earlier (such as in
836 // mapThemeChanged slot) then this xml could be out of date...
837 // TODO: if in future QgsMapThemeCollection::mapThemeStyleOverrides is changed to
838 // just return the style name, we can instead set the overrides in mapThemeChanged and not here
839 mSettings.setLayerStyleOverrides( QgsProject::instance()->mapThemeCollection()->mapThemeStyleOverrides( mTheme ) );
840 }
841
842 // render main annotation layer above all other layers
843 QgsMapSettings renderSettings = mSettings;
844 QList<QgsMapLayer *> allLayers = renderSettings.layers();
846 allLayers.insert( 0, QgsProject::instance()->mainAnnotationLayer() );
847
848 renderSettings.setLayers( filterLayersForRender( allLayers ) );
849
850 // create the renderer job
851
852 QgsApplication::profiler()->clear( u"rendering"_s );
853
854 Q_ASSERT( !mJob );
855 mJobCanceled = false;
856 if ( mUseParallelRendering )
857 mJob = new QgsMapRendererParallelJob( renderSettings );
858 else
859 mJob = new QgsMapRendererSequentialJob( renderSettings );
860
861 connect( mJob, &QgsMapRendererJob::finished, this, &QgsMapCanvas::rendererJobFinished );
862 mJob->setCache( mCache.get() );
863 mJob->setLayerRenderingTimeHints( mLastLayerRenderTime );
864
865 mJob->start();
866
867 // from now on we can accept refresh requests again
868 // this must be reset only after the job has been started, because
869 // some providers (yes, it's you WCS and AMS!) during preparation
870 // do network requests and start an internal event loop, which may
871 // end up calling refresh() and would schedule another refresh,
872 // deleting the one we have just started.
873 mRefreshScheduled = false;
874
875 mMapUpdateTimer.start();
876
877 emit renderStarting();
878}
879
880void QgsMapCanvas::mapThemeChanged( const QString &theme )
881{
882 if ( theme == mTheme )
883 {
884 // set the canvas layers to match the new layers contained in the map theme
885 // NOTE: we do this when the theme layers change and not when we are refreshing the map
886 // as setLayers() sets up necessary connections to handle changes to the layers
887 setLayersPrivate( QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
888 // IMPORTANT: we don't set the layer style overrides here! (At the time of writing this
889 // comment) retrieving layer styles from the theme collection gives an XML snapshot of the
890 // current state of the style. If changes were made to the style then this xml
891 // snapshot goes out of sync...
892 // TODO: if in future QgsMapThemeCollection::mapThemeStyleOverrides is changed to
893 // just return the style name, we can instead set the overrides here and not in refreshMap()
894
895 clearCache();
896 refresh();
897 }
898}
899
900void QgsMapCanvas::mapThemeRenamed( const QString &theme, const QString &newTheme )
901{
902 if ( mTheme.isEmpty() || theme != mTheme )
903 {
904 return;
905 }
906
907 setTheme( newTheme );
908 refresh();
909}
910
911void QgsMapCanvas::rendererJobFinished()
912{
913 QgsDebugMsgLevel( u"CANVAS finish! %1"_s.arg( !mJobCanceled ), 2 );
914
915 mMapUpdateTimer.stop();
916
917 notifyRendererErrors( mJob->errors() );
918
919 if ( !mJobCanceled )
920 {
921 // take labeling results before emitting renderComplete, so labeling map tools
922 // connected to signal work with correct results
923 if ( !mJob->usedCachedLabels() )
924 {
925 mLabelingResults.reset( mJob->takeLabelingResults() );
926 }
927 mLabelingResultsOutdated = false;
928
929 std::unique_ptr<QgsRenderedItemResults> renderedItemResults( mJob->takeRenderedItemResults() );
930 // if a layer was redrawn from the cached version, we should copy any existing rendered item results from that layer
931 if ( mRenderedItemResults )
932 {
933 renderedItemResults->transferResults( mRenderedItemResults.get(), mJob->layersRedrawnFromCache() );
934 }
935 if ( mPreviousRenderedItemResults )
936 {
937 // also transfer any results from previous renders which happened before this
938 renderedItemResults->transferResults( mPreviousRenderedItemResults.get(), mJob->layersRedrawnFromCache() );
939 }
940
941 if ( mCache && !mPreviousRenderedItemResults )
942 mPreviousRenderedItemResults = std::make_unique<QgsRenderedItemResults>( mJob->mapSettings().extent() );
943
944 if ( mRenderedItemResults && mPreviousRenderedItemResults )
945 {
946 // for other layers which ARE present in the most recent rendered item results BUT were not part of this render, we
947 // store the results in a temporary store in case they are later switched back on and the layer's image is taken
948 // from the cache
949 mPreviousRenderedItemResults->transferResults( mRenderedItemResults.get() );
950 }
951 if ( mPreviousRenderedItemResults )
952 {
953 mPreviousRenderedItemResults->eraseResultsFromLayers( mJob->mapSettings().layerIds() );
954 }
955
956 mRenderedItemResults = std::move( renderedItemResults );
957 mRenderedItemResultsOutdated = false;
958
959 QImage img = mJob->renderedImage();
960
961 // emit renderComplete to get our decorations drawn and to handle computed statistics
962 QPainter p( &img );
963 emit renderComplete( &p );
964
966 {
967 QString logMsg = tr( "Canvas refresh: %1 ms" ).arg( mJob->renderingTime() );
968 QgsMessageLog::logMessage( logMsg, tr( "Rendering" ) );
969 }
970
971 if ( mDrawRenderingStats )
972 {
973 int w = img.width(), h = img.height();
974 QFont fnt = p.font();
975 fnt.setBold( true );
976 p.setFont( fnt );
977 int lh = p.fontMetrics().height() * 2;
978 QRect r( 0, h - lh, w, lh );
979 p.setPen( Qt::NoPen );
980 p.setBrush( QColor( 0, 0, 0, 110 ) );
981 p.drawRect( r );
982 p.setPen( Qt::white );
983 QString msg = u"%1 :: %2 ms"_s.arg( mUseParallelRendering ? u"PARALLEL"_s : u"SEQUENTIAL"_s ).arg( mJob->renderingTime() );
984 p.drawText( r, msg, QTextOption( Qt::AlignCenter ) );
985 }
986
987 p.end();
988
989 mMap->setContent( img, imageRect( img, mSettings ) );
990
991 mLastLayerRenderTime.clear();
992 const auto times = mJob->perLayerRenderingTime();
993 for ( auto it = times.constBegin(); it != times.constEnd(); ++it )
994 {
995 mLastLayerRenderTime.insert( it.key()->id(), it.value() );
996 }
997 if ( mUsePreviewJobs && !mRefreshAfterJob )
998 startPreviewJobs();
999 }
1000 else
1001 {
1002 mRefreshAfterJob = false;
1003 }
1004
1005 // now we are in a slot called from mJob - do not delete it immediately
1006 // so the class is still valid when the execution returns to the class
1007 mJob->deleteLater();
1008 mJob = nullptr;
1009
1010 emit mapCanvasRefreshed();
1011
1012 if ( mRefreshAfterJob )
1013 {
1014 mRefreshAfterJob = false;
1015 refresh();
1016 }
1017}
1018
1019void QgsMapCanvas::previewJobFinished()
1020{
1021 QgsMapRendererQImageJob *job = qobject_cast<QgsMapRendererQImageJob *>( sender() );
1022 Q_ASSERT( job );
1023
1024 if ( mMap )
1025 {
1026 mMap->addPreviewImage( job->renderedImage(), job->mapSettings().visiblePolygon() );
1027 mPreviewJobs.removeAll( job );
1028
1029 int number = job->property( "number" ).toInt();
1030 if ( number < 8 )
1031 {
1032 startPreviewJob( number + 1 );
1033 }
1034
1035 delete job;
1036 }
1037}
1038
1039QgsRectangle QgsMapCanvas::imageRect( const QImage &img, const QgsMapSettings &mapSettings )
1040{
1041 // This is a hack to pass QgsMapCanvasItem::setRect what it
1042 // expects (encoding of position and size of the item)
1043 const QgsMapToPixel &m2p = mapSettings.mapToPixel();
1044 QgsPointXY topLeft = m2p.toMapCoordinates( 0, 0 );
1045#ifdef QGISDEBUG
1046 // do not assert this, since it might lead to crashes when changing screen while rendering
1047 if ( img.devicePixelRatio() != mapSettings.devicePixelRatio() )
1048 {
1049 QgsLogger::warning( u"The renderer map has a wrong device pixel ratio"_s );
1050 }
1051#endif
1052 double res = m2p.mapUnitsPerPixel() / img.devicePixelRatioF();
1053 QgsRectangle rect( topLeft.x(), topLeft.y(), topLeft.x() + img.width() * res, topLeft.y() - img.height() * res );
1054 return rect;
1055}
1056
1058{
1059 return mStatusBar.data();
1060}
1061
1063{
1064 mStatusBar = bar;
1065}
1066
1068{
1069 return mUsePreviewJobs;
1070}
1071
1073{
1074 mUsePreviewJobs = enabled;
1075}
1076
1077void QgsMapCanvas::setCustomDropHandlers( const QVector<QPointer<QgsCustomDropHandler>> &handlers )
1078{
1079 mDropHandlers = handlers;
1080}
1081
1082void QgsMapCanvas::clearTemporalCache()
1083{
1084 if ( mCache )
1085 {
1086 bool invalidateLabels = false;
1087 const QList<QgsMapLayer *> layerList = mapSettings().layers();
1088 for ( QgsMapLayer *layer : layerList )
1089 {
1090 bool alreadyInvalidatedThisLayer = false;
1091 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
1092 {
1093 if ( vl->renderer() && QgsSymbolLayerUtils::rendererFrameRate( vl->renderer() ) > -1 )
1094 {
1095 // layer has an animated symbol assigned, so we have to redraw it regardless of whether
1096 // or not it has temporal settings
1097 mCache->invalidateCacheForLayer( layer );
1098 alreadyInvalidatedThisLayer = true;
1099 // we can't shortcut and "continue" here, as we still need to check whether the layer
1100 // will cause label invalidation using the logic below
1101 }
1102 }
1103
1104 if ( layer->temporalProperties() && layer->temporalProperties()->isActive() )
1105 {
1106 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
1107 {
1108 if ( vl->labelsEnabled() || vl->diagramsEnabled() || ( vl->renderer() && vl->renderer()->flags().testFlag( Qgis::FeatureRendererFlag::AffectsLabeling ) ) )
1109 invalidateLabels = true;
1110 }
1111
1113 continue;
1114
1115 if ( !alreadyInvalidatedThisLayer )
1116 {
1117 mCache->invalidateCacheForLayer( layer );
1118 }
1119 }
1120 else if ( QgsGroupLayer *gl = qobject_cast<QgsGroupLayer *>( layer ) )
1121 {
1122 const QList<QgsMapLayer *> childLayerList = gl->childLayers();
1123 for ( QgsMapLayer *childLayer : childLayerList )
1124 {
1125 if ( childLayer->temporalProperties() && childLayer->temporalProperties()->isActive() )
1126 {
1127 if ( childLayer->temporalProperties()->flags() & QgsTemporalProperty::FlagDontInvalidateCachedRendersWhenRangeChanges )
1128 continue;
1129
1130 mCache->invalidateCacheForLayer( layer );
1131 break;
1132 }
1133 }
1134 }
1135 }
1136
1137 if ( invalidateLabels )
1138 {
1139 mCache->clearCacheImage( u"_labels_"_s );
1140 mCache->clearCacheImage( u"_preview_labels_"_s );
1141 }
1142 }
1143}
1144
1145void QgsMapCanvas::clearElevationCache()
1146{
1147 if ( mCache )
1148 {
1149 bool invalidateLabels = false;
1150 const QList<QgsMapLayer *> layerList = mapSettings().layers();
1151 for ( QgsMapLayer *layer : layerList )
1152 {
1153 if ( layer->elevationProperties() && layer->elevationProperties()->hasElevation() )
1154 {
1155 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
1156 {
1157 if ( vl->labelsEnabled() || vl->diagramsEnabled() || ( vl->renderer() && vl->renderer()->flags().testFlag( Qgis::FeatureRendererFlag::AffectsLabeling ) ) )
1158 invalidateLabels = true;
1159 }
1160
1162 continue;
1163
1164 mCache->invalidateCacheForLayer( layer );
1165 }
1166 else if ( QgsGroupLayer *gl = qobject_cast<QgsGroupLayer *>( layer ) )
1167 {
1168 const QList<QgsMapLayer *> childLayerList = gl->childLayers();
1169 for ( QgsMapLayer *childLayer : childLayerList )
1170 {
1171 if ( childLayer->elevationProperties() && childLayer->elevationProperties()->hasElevation() )
1172 {
1173 if ( childLayer->elevationProperties()->flags() & QgsMapLayerElevationProperties::FlagDontInvalidateCachedRendersWhenRangeChanges )
1174 continue;
1175
1176 mCache->invalidateCacheForLayer( layer );
1177 break;
1178 }
1179 }
1180 }
1181 }
1182
1183 if ( invalidateLabels )
1184 {
1185 mCache->clearCacheImage( u"_labels_"_s );
1186 mCache->clearCacheImage( u"_preview_labels_"_s );
1187 }
1188 }
1189}
1190
1191void QgsMapCanvas::showContextMenu( QgsMapMouseEvent *event )
1192{
1193 const QgsPointXY mapPoint = event->originalMapPoint();
1194
1195 QMenu menu;
1196
1197 QMenu *copyCoordinateMenu = new QMenu( tr( "Copy Coordinate" ), &menu );
1198 copyCoordinateMenu->setIcon( QgsApplication::getThemeIcon( u"/mActionEditCopy.svg"_s ) );
1199
1200 auto addCoordinateFormat = [&, this]( const QString identifier, const QgsCoordinateReferenceSystem &crs ) {
1201 const QgsCoordinateTransform ct( mSettings.destinationCrs(), crs, mSettings.transformContext() );
1202 try
1203 {
1204 const QgsPointXY transformedPoint = ct.transform( mapPoint );
1205
1206 // calculate precision based on visible map extent -- if user is zoomed in, we get better precision!
1207 int displayPrecision = 0;
1208 try
1209 {
1210 QgsCoordinateTransform extentTransform = ct;
1211 extentTransform.setBallparkTransformsAreAppropriate( true );
1212 QgsRectangle extentReproj = extentTransform.transformBoundingBox( extent() );
1213 const double mapUnitsPerPixel = ( extentReproj.width() / width() + extentReproj.height() / height() ) * 0.5;
1214 if ( mapUnitsPerPixel > 10 )
1215 displayPrecision = 0;
1216 else if ( mapUnitsPerPixel > 1 )
1217 displayPrecision = 1;
1218 else if ( mapUnitsPerPixel > 0.1 )
1219 displayPrecision = 2;
1220 else if ( mapUnitsPerPixel > 0.01 )
1221 displayPrecision = 3;
1222 else if ( mapUnitsPerPixel > 0.001 )
1223 displayPrecision = 4;
1224 else if ( mapUnitsPerPixel > 0.0001 )
1225 displayPrecision = 5;
1226 else if ( mapUnitsPerPixel > 0.00001 )
1227 displayPrecision = 6;
1228 else if ( mapUnitsPerPixel > 0.000001 )
1229 displayPrecision = 7;
1230 else if ( mapUnitsPerPixel > 0.0000001 )
1231 displayPrecision = 8;
1232 else
1233 displayPrecision = 9;
1234 }
1235 catch ( QgsCsException & )
1236 {
1237 displayPrecision = crs.mapUnits() == Qgis::DistanceUnit::Degrees ? 5 : 3;
1238 }
1239
1240 const QList<Qgis::CrsAxisDirection> axisList = crs.axisOrdering();
1241 QString firstSuffix;
1242 QString secondSuffix;
1243 if ( axisList.size() >= 2 )
1244 {
1247 }
1248
1249 QString firstNumber;
1250 QString secondNumber;
1252 {
1253 firstNumber = QString::number( transformedPoint.y(), 'f', displayPrecision );
1254 secondNumber = QString::number( transformedPoint.x(), 'f', displayPrecision );
1255 }
1256 else
1257 {
1258 firstNumber = QString::number( transformedPoint.x(), 'f', displayPrecision );
1259 secondNumber = QString::number( transformedPoint.y(), 'f', displayPrecision );
1260 }
1261
1262 QAction *copyCoordinateAction = new QAction( u"%5 (%1%2, %3%4)"_s.arg( firstNumber, firstSuffix, secondNumber, secondSuffix, identifier ), &menu );
1263
1264 connect( copyCoordinateAction, &QAction::triggered, this, [firstNumber, firstSuffix, secondNumber, secondSuffix, transformedPoint] {
1265 QClipboard *clipboard = QApplication::clipboard();
1266
1267 const QString coordinates = u"%1%2, %3%4"_s.arg( firstNumber, firstSuffix, secondNumber, secondSuffix );
1268
1269 //if we are on x11 system put text into selection ready for middle button pasting
1270 if ( clipboard->supportsSelection() )
1271 {
1272 clipboard->setText( coordinates, QClipboard::Selection );
1273 }
1274 clipboard->setText( coordinates, QClipboard::Clipboard );
1275 } );
1276 copyCoordinateMenu->addAction( copyCoordinateAction );
1277 }
1278 catch ( QgsCsException & )
1279 {}
1280 };
1281
1282 addCoordinateFormat( tr( "Map CRS — %1" ).arg( mSettings.destinationCrs().userFriendlyIdentifier( Qgis::CrsIdentifierType::MediumString ) ), mSettings.destinationCrs() );
1283 QgsCoordinateReferenceSystem wgs84( u"EPSG:4326"_s );
1284 if ( mSettings.destinationCrs() != wgs84 )
1285 addCoordinateFormat( wgs84.userFriendlyIdentifier( Qgis::CrsIdentifierType::MediumString ), wgs84 );
1286
1287 QgsSettings settings;
1288 const QString customCrsString = QgsMapCanvas::settingsCustomCoordinateCrs->value();
1289 if ( !customCrsString.isEmpty() )
1290 {
1291 QgsCoordinateReferenceSystem customCrs( customCrsString );
1292 if ( customCrs != mSettings.destinationCrs() && customCrs != QgsCoordinateReferenceSystem( u"EPSG:4326"_s ) )
1293 {
1294 addCoordinateFormat( customCrs.userFriendlyIdentifier( Qgis::CrsIdentifierType::MediumString ), customCrs );
1295 }
1296 }
1297 copyCoordinateMenu->addSeparator();
1298 QAction *setCustomCrsAction = new QAction( tr( "Set Custom CRS…" ), &menu );
1299 connect( setCustomCrsAction, &QAction::triggered, this, [this, customCrsString] {
1300 QgsProjectionSelectionDialog selector( this );
1301 selector.setCrs( QgsCoordinateReferenceSystem( customCrsString ) );
1302 if ( selector.exec() )
1303 {
1304 QgsMapCanvas::settingsCustomCoordinateCrs->setValue( selector.crs().authid().isEmpty() ? selector.crs().toWkt( Qgis::CrsWktVariant::Preferred ) : selector.crs().authid() );
1305 }
1306 } );
1307 copyCoordinateMenu->addAction( setCustomCrsAction );
1308
1309 menu.addMenu( copyCoordinateMenu );
1310
1311 if ( mMapTool )
1312 if ( !mapTool()->populateContextMenuWithEvent( &menu, event ) )
1313 mMapTool->populateContextMenu( &menu );
1314
1315 emit contextMenuAboutToShow( &menu, event );
1316
1317 if ( !menu.isEmpty() ) // menu can be empty after populateContextMenu() and contextMenuAboutToShow()
1318 menu.exec( event->globalPos() );
1319}
1320
1321void QgsMapCanvas::notifyRendererErrors( const QgsMapRendererJob::Errors &errors )
1322{
1323 const QDateTime currentTime = QDateTime::currentDateTime();
1324
1325 // remove errors too old
1326 for ( const QgsMapRendererJob::Error &error : errors )
1327 {
1328 const QString errorKey = error.layerID + ':' + error.message;
1329 if ( mRendererErrors.contains( errorKey ) )
1330 {
1331 const QDateTime sameErrorTime = mRendererErrors.value( errorKey );
1332
1333 if ( sameErrorTime.secsTo( currentTime ) < 60 )
1334 continue;
1335 }
1336
1337 mRendererErrors[errorKey] = currentTime;
1338
1339 if ( QgsMapLayer *layer = QgsProject::instance()->mapLayer( error.layerID ) )
1340 emit renderErrorOccurred( error.message, layer );
1341 }
1342}
1343
1344void QgsMapCanvas::updateDevicePixelFromScreen()
1345{
1346 mSettings.setDevicePixelRatio( static_cast<float>( devicePixelRatioF() ) );
1347 // TODO: QGIS 5 -> always respect screen dpi
1349 {
1350 if ( window()->windowHandle() )
1351 {
1352 mSettings.setOutputDpi( window()->windowHandle()->screen()->physicalDotsPerInch() );
1353 mSettings.setDpiTarget( window()->windowHandle()->screen()->physicalDotsPerInch() );
1354 }
1355 }
1356 else
1357 {
1358 // Fallback: compatibility with QGIS <= 3.20; always assume low dpi screens
1359 mSettings.setOutputDpi( window()->windowHandle()->screen()->logicalDotsPerInch() );
1360 mSettings.setDpiTarget( window()->windowHandle()->screen()->logicalDotsPerInch() );
1361 }
1362 refresh();
1363}
1364
1365void QgsMapCanvas::onElevationShadingRendererChanged()
1366{
1367 if ( !mProject )
1368 return;
1369 bool wasDeactivated = !mSettings.elevationShadingRenderer().isActive();
1370 mSettings.setElevationShadingRenderer( mProject->elevationShadingRenderer() );
1371 if ( mCache && wasDeactivated )
1372 mCache->clear();
1373 refresh();
1374}
1375
1377{
1378 if ( temporalRange() == dateTimeRange )
1379 return;
1380
1381 mSettings.setTemporalRange( dateTimeRange );
1382 mSettings.setIsTemporal( dateTimeRange.begin().isValid() || dateTimeRange.end().isValid() );
1383
1384 emit temporalRangeChanged();
1385
1386 // we need to discard any previously cached images which have temporal properties enabled, so that these will be updated when
1387 // the canvas is redrawn
1388 mCacheInvalidations |= CacheInvalidationType::Temporal;
1389
1390 autoRefreshTriggered();
1391}
1392
1394{
1395 return mSettings.temporalRange();
1396}
1397
1399{
1400 mInteractionBlockers.append( blocker );
1401}
1402
1404{
1405 mInteractionBlockers.removeAll( blocker );
1406}
1407
1409{
1410 for ( const QgsMapCanvasInteractionBlocker *block : mInteractionBlockers )
1411 {
1412 if ( block->blockCanvasInteraction( interaction ) )
1413 return false;
1414 }
1415 return true;
1416}
1417
1419{
1420 if ( mMapController )
1421 {
1422 delete mMapController;
1423 mMapController = nullptr;
1424 }
1425
1426 if ( !controller )
1427 return;
1428
1429 mMapController = controller;
1430 mMapController->setParent( this );
1431
1432#if 0
1433 // connect high level signals to the canvas, e.g.
1434 connect( mMapController, &QgsAbstract2DMapController::zoomMap, this, []( double factor ) { zoomByFactor( factor ); } );
1435#endif
1436}
1437
1438void QgsMapCanvas::mapUpdateTimeout()
1439{
1440 if ( mJob )
1441 {
1442 const QImage &img = mJob->renderedImage();
1443 mMap->setContent( img, imageRect( img, mSettings ) );
1444 }
1445}
1446
1448{
1449 if ( mJob )
1450 {
1451 QgsDebugMsgLevel( u"CANVAS stop rendering!"_s, 2 );
1452 mJobCanceled = true;
1453 disconnect( mJob, &QgsMapRendererJob::finished, this, &QgsMapCanvas::rendererJobFinished );
1454 connect( mJob, &QgsMapRendererQImageJob::finished, mJob, &QgsMapRendererQImageJob::deleteLater );
1455 mJob->cancelWithoutBlocking();
1456 mJob = nullptr;
1457 emit mapRefreshCanceled();
1458 }
1459 stopPreviewJobs();
1460}
1461
1462//the format defaults to "PNG" if not specified
1463void QgsMapCanvas::saveAsImage( const QString &fileName, QPixmap *theQPixmap, const QString &format )
1464{
1465 QPainter painter;
1466 QImage image;
1467
1468 //
1469 //check if the optional QPaintDevice was supplied
1470 //
1471 if ( theQPixmap )
1472 {
1473 image = theQPixmap->toImage();
1474 painter.begin( &image );
1475
1476 // render
1477 QgsMapRendererCustomPainterJob job( mSettings, &painter );
1478 job.start();
1479 job.waitForFinished();
1480 emit renderComplete( &painter );
1481 }
1482 else //use the map view
1483 {
1484 image = mMap->contentImage().copy();
1485 painter.begin( &image );
1486 }
1487
1488 // draw annotations
1489 QStyleOptionGraphicsItem option;
1490 option.initFrom( this );
1491 QGraphicsItem *item = nullptr;
1492 QListIterator<QGraphicsItem *> i( items() );
1493 i.toBack();
1494 while ( i.hasPrevious() )
1495 {
1496 item = i.previous();
1497
1498 if ( !( item && dynamic_cast<QgsMapCanvasAnnotationItem *>( item ) ) )
1499 {
1500 continue;
1501 }
1502
1503 QgsScopedQPainterState painterState( &painter );
1504
1505 QPointF itemScenePos = item->scenePos();
1506 painter.translate( itemScenePos.x(), itemScenePos.y() );
1507
1508 item->paint( &painter, &option );
1509 }
1510
1511 painter.end();
1512 image.save( fileName, format.toLocal8Bit().data() );
1513
1514 QFileInfo myInfo = QFileInfo( fileName );
1515
1516 // build the world file name
1517 QString outputSuffix = myInfo.suffix();
1518 QString myWorldFileName = myInfo.absolutePath() + '/' + myInfo.completeBaseName() + '.' + outputSuffix.at( 0 ) + outputSuffix.at( myInfo.suffix().size() - 1 ) + 'w';
1519 QFile myWorldFile( myWorldFileName );
1520 if ( !myWorldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) //don't use QIODevice::Text
1521 {
1522 return;
1523 }
1524 QTextStream myStream( &myWorldFile );
1526}
1527
1529{
1530 return mapSettings().visibleExtent();
1531}
1532
1534{
1535 return QgsMapLayerUtils::combinedExtent( mSettings.layers(), mapSettings().destinationCrs(), QgsProject::instance()->transformContext() );
1536}
1537
1539{
1540 const QgsReferencedRectangle extent = mProject ? mProject->viewSettings()->fullExtent() : QgsProject::instance()->viewSettings()->fullExtent();
1541 QgsCoordinateTransform ct( extent.crs(), mapSettings().destinationCrs(), mProject ? mProject->transformContext() : QgsProject::instance()->transformContext() );
1543 QgsRectangle rect;
1544 try
1545 {
1546 rect = ct.transformBoundingBox( extent );
1547 }
1548 catch ( QgsCsException & )
1549 {
1550 rect = mapSettings().fullExtent();
1551 }
1552
1553 return rect;
1554}
1555
1556void QgsMapCanvas::setExtent( const QgsRectangle &r, bool magnified )
1557{
1558 QgsRectangle current = extent();
1559
1560 if ( ( r == current ) && magnified )
1561 return;
1562
1563 if ( r.isEmpty() )
1564 {
1565 if ( !mSettings.hasValidSettings() )
1566 {
1567 // we can't even just move the map center
1568 QgsDebugMsgLevel( u"Empty extent - ignoring"_s, 2 );
1569 return;
1570 }
1571
1572 // ### QGIS 3: do not allow empty extent - require users to call setCenter() explicitly
1573 QgsDebugMsgLevel( u"Empty extent - keeping old scale with new center!"_s, 2 );
1574
1575 setCenter( r.center() );
1576 }
1577 else
1578 {
1579 // If scale is locked we need to maintain the current scale, so we
1580 // - magnify and recenter the map
1581 // - restore locked scale
1582 if ( mScaleLocked && magnified )
1583 {
1584 ScaleRestorer restorer( this );
1585 const double ratio { mapSettings().extent().width() / mapSettings().extent().height() };
1586 const double factor { r.width() / r.height() > ratio ? mapSettings().extent().width() / r.width() : mapSettings().extent().height() / r.height() };
1587 const double scaleFactor { std::clamp( mSettings.magnificationFactor() * factor, QgsGuiUtils::CANVAS_MAGNIFICATION_MIN, QgsGuiUtils::CANVAS_MAGNIFICATION_MAX ) };
1588 const QgsPointXY newCenter { r.center() };
1589 mSettings.setMagnificationFactor( scaleFactor, &newCenter );
1590 emit magnificationChanged( scaleFactor );
1591 }
1592 else
1593 {
1594 mSettings.setExtent( r, magnified );
1595 }
1596 }
1598 updateScale();
1599
1600 //clear all extent items after current index
1601 for ( int i = mLastExtent.size() - 1; i > mLastExtentIndex; i-- )
1602 {
1603 mLastExtent.removeAt( i );
1604 }
1605
1606 if ( !mLastExtent.isEmpty() && mLastExtent.last() != mSettings.extent() )
1607 {
1608 mLastExtent.append( mSettings.extent() );
1609 }
1610
1611 // adjust history to no more than 100
1612 if ( mLastExtent.size() > 100 )
1613 {
1614 mLastExtent.removeAt( 0 );
1615 }
1616
1617 // the last item is the current extent
1618 mLastExtentIndex = mLastExtent.size() - 1;
1619
1620 // update controls' enabled state
1621 emit zoomLastStatusChanged( mLastExtentIndex > 0 );
1622 emit zoomNextStatusChanged( mLastExtentIndex < mLastExtent.size() - 1 );
1623}
1624
1626{
1627 QgsRectangle canvasExtent = extent;
1628 if ( extent.crs() != mapSettings().destinationCrs() )
1629 {
1630 QgsCoordinateTransform ct( extent.crs(), mapSettings().destinationCrs(), QgsProject::instance() );
1632 canvasExtent = ct.transformBoundingBox( extent );
1633
1634 if ( canvasExtent.isEmpty() )
1635 {
1636 return false;
1637 }
1638 }
1639
1640 setExtent( canvasExtent, true );
1641 return true;
1642}
1643
1645{
1646 const QgsRectangle r = mapSettings().extent();
1647 const double xMin = center.x() - r.width() / 2.0;
1648 const double yMin = center.y() - r.height() / 2.0;
1649 const QgsRectangle rect( xMin, yMin, xMin + r.width(), yMin + r.height() );
1650 if ( !rect.isEmpty() )
1651 {
1652 setExtent( rect, true );
1653 }
1654} // setCenter
1655
1657{
1659 return r.center();
1660}
1661
1662QgsPointXY QgsMapCanvas::cursorPoint() const
1663{
1664 return mCursorPoint;
1665}
1666
1668{
1669 return mapSettings().rotation();
1670}
1671
1672void QgsMapCanvas::setRotation( double degrees )
1673{
1674 double current = rotation();
1675
1676 if ( qgsDoubleNear( degrees, current ) )
1677 return;
1678
1679 mSettings.setRotation( degrees );
1680 emit rotationChanged( degrees );
1681 emitExtentsChanged(); // visible extent changes with rotation
1682}
1683
1685{
1686 if ( !mBlockScaleChangedSignal )
1687 emit scaleChanged( mapSettings().scale() );
1688}
1689
1691{
1693 // If the full extent is an empty set, don't do the zoom
1694 if ( !extent.isEmpty() )
1695 {
1696 // Add a 5% margin around the full extent
1697 extent.scale( 1.05 );
1698 setExtent( extent, true );
1699 }
1700 refresh();
1701}
1702
1704{
1706
1707 // If the full extent is an empty set, don't do the zoom
1708 if ( !extent.isEmpty() )
1709 {
1710 // Add a 5% margin around the full extent
1711 extent.scale( 1.05 );
1712 setExtent( extent, true );
1713 }
1714 refresh();
1715}
1716
1718{
1719 if ( mLastExtentIndex > 0 )
1720 {
1721 mLastExtentIndex--;
1722 mSettings.setExtent( mLastExtent[mLastExtentIndex] );
1724 updateScale();
1725 refresh();
1726 // update controls' enabled state
1727 emit zoomLastStatusChanged( mLastExtentIndex > 0 );
1728 emit zoomNextStatusChanged( mLastExtentIndex < mLastExtent.size() - 1 );
1729 }
1730
1731} // zoomToPreviousExtent
1732
1734{
1735 if ( mLastExtentIndex < mLastExtent.size() - 1 )
1736 {
1737 mLastExtentIndex++;
1738 mSettings.setExtent( mLastExtent[mLastExtentIndex] );
1740 updateScale();
1741 refresh();
1742 // update controls' enabled state
1743 emit zoomLastStatusChanged( mLastExtentIndex > 0 );
1744 emit zoomNextStatusChanged( mLastExtentIndex < mLastExtent.size() - 1 );
1745 }
1746} // zoomToNextExtent
1747
1749{
1750 mLastExtent.clear(); // clear the zoom history list
1751 mLastExtent.append( mSettings.extent() ); // set the current extent in the list
1752 mLastExtentIndex = mLastExtent.size() - 1;
1753 // update controls' enabled state
1754 emit zoomLastStatusChanged( mLastExtentIndex > 0 );
1755 emit zoomNextStatusChanged( mLastExtentIndex < mLastExtent.size() - 1 );
1756} // clearExtentHistory
1757
1758QgsRectangle QgsMapCanvas::optimalExtentForPointLayer( QgsVectorLayer *layer, const QgsPointXY &center, int scaleFactor )
1759{
1760 QgsRectangle rect( center, center );
1761
1762 if ( layer->geometryType() == Qgis::GeometryType::Point )
1763 {
1764 QgsPointXY centerLayerCoordinates = mSettings.mapToLayerCoordinates( layer, center );
1765 QgsRectangle extentRect = mSettings.mapToLayerCoordinates( layer, extent() ).scaled( 1.0 / scaleFactor, &centerLayerCoordinates );
1767 QgsFeatureIterator fit = layer->getFeatures( req );
1768 QgsFeature f;
1769 QgsPointXY closestPoint;
1770 double closestSquaredDistance = pow( extentRect.width(), 2.0 ) + pow( extentRect.height(), 2.0 );
1771 bool pointFound = false;
1772 while ( fit.nextFeature( f ) )
1773 {
1774 QgsPointXY point = f.geometry().asPoint();
1775 double sqrDist = point.sqrDist( centerLayerCoordinates );
1776 if ( sqrDist > closestSquaredDistance || sqrDist < 4 * std::numeric_limits<double>::epsilon() )
1777 continue;
1778 pointFound = true;
1779 closestPoint = point;
1780 closestSquaredDistance = sqrDist;
1781 }
1782 if ( pointFound )
1783 {
1784 // combine selected point with closest point and scale this rect
1785 rect.combineExtentWith( mSettings.layerToMapCoordinates( layer, closestPoint ) );
1786 rect.scale( scaleFactor, &center );
1787 }
1788 }
1789 return rect;
1790}
1791
1793{
1794 QgsTemporaryCursorOverride cursorOverride( Qt::WaitCursor );
1795
1796 if ( !layer )
1797 {
1798 // use current layer by default
1799 layer = mCurrentLayer;
1800 }
1801
1802 if ( !layer || !layer->isSpatial() )
1803 return;
1804
1805 QgsRectangle rect;
1806
1807 switch ( layer->type() )
1808 {
1810 {
1811 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
1812 if ( vlayer->selectedFeatureCount() == 0 )
1813 return;
1814
1815 rect = vlayer->boundingBoxOfSelected();
1816 if ( rect.isNull() )
1817 {
1818 cursorOverride.release();
1819 emit messageEmitted( tr( "Cannot zoom to selected feature(s)" ), tr( "No extent could be determined." ), Qgis::MessageLevel::Warning );
1820 return;
1821 }
1822
1824
1825 // zoom in if point cannot be distinguished from others
1826 // also check that rect is empty, as it might not in case of multi points
1827 if ( vlayer->geometryType() == Qgis::GeometryType::Point && rect.isEmpty() )
1828 {
1829 rect = optimalExtentForPointLayer( vlayer, rect.center() );
1830 }
1831 break;
1832 }
1833
1835 {
1836 QgsVectorTileLayer *vtLayer = qobject_cast<QgsVectorTileLayer *>( layer );
1837 if ( vtLayer->selectedFeatureCount() == 0 )
1838 return;
1839
1840 const QList<QgsFeature> selectedFeatures = vtLayer->selectedFeatures();
1841 for ( const QgsFeature &feature : selectedFeatures )
1842 {
1843 if ( !feature.hasGeometry() )
1844 continue;
1845
1846 rect.combineExtentWith( feature.geometry().boundingBox() );
1847 }
1848
1849 if ( rect.isNull() )
1850 {
1851 cursorOverride.release();
1852 emit messageEmitted( tr( "Cannot zoom to selected feature(s)" ), tr( "No extent could be determined." ), Qgis::MessageLevel::Warning );
1853 return;
1854 }
1855
1857 break;
1858 }
1859
1867 return; // not supported
1868 }
1869
1870 zoomToFeatureExtent( rect );
1871}
1872
1873void QgsMapCanvas::zoomToSelected( const QList<QgsMapLayer *> &layers )
1874{
1875 QgsRectangle rect;
1876 rect.setNull();
1877 QgsRectangle selectionExtent;
1878 selectionExtent.setNull();
1879
1880 for ( QgsMapLayer *mapLayer : layers )
1881 {
1882 if ( !mapLayer || !mapLayer->isSpatial() )
1883 continue;
1884
1885 switch ( mapLayer->type() )
1886 {
1888 {
1889 QgsVectorLayer *layer = qobject_cast<QgsVectorLayer *>( mapLayer );
1890
1891 if ( layer->selectedFeatureCount() == 0 )
1892 continue;
1893
1894 rect = layer->boundingBoxOfSelected();
1895
1896 if ( rect.isNull() )
1897 continue;
1898
1900
1901 if ( layer->geometryType() == Qgis::GeometryType::Point && rect.isEmpty() )
1902 rect = optimalExtentForPointLayer( layer, rect.center() );
1903
1904 selectionExtent.combineExtentWith( rect );
1905 break;
1906 }
1907
1909 {
1910 QgsVectorTileLayer *vtLayer = qobject_cast<QgsVectorTileLayer *>( mapLayer );
1911 if ( vtLayer->selectedFeatureCount() == 0 )
1912 continue;
1913
1914 const QList<QgsFeature> selectedFeatures = vtLayer->selectedFeatures();
1915 QgsRectangle rect;
1916 for ( const QgsFeature &feature : selectedFeatures )
1917 {
1918 if ( !feature.hasGeometry() )
1919 continue;
1920
1921 rect.combineExtentWith( feature.geometry().boundingBox() );
1922 }
1923
1924 rect = mapSettings().layerExtentToOutputExtent( vtLayer, rect );
1925 selectionExtent.combineExtentWith( rect );
1926 break;
1927 }
1928
1936 break;
1937 }
1938 }
1939
1940 if ( selectionExtent.isNull() )
1941 {
1942 emit messageEmitted( tr( "Cannot zoom to selected feature(s)" ), tr( "No extent could be determined." ), Qgis::MessageLevel::Warning );
1943 return;
1944 }
1945
1946 zoomToFeatureExtent( selectionExtent );
1947}
1948
1950{
1951 return mSettings.zRange();
1952}
1953
1955{
1956 if ( zRange() == range )
1957 return;
1958
1959 mSettings.setZRange( range );
1960
1961 emit zRangeChanged();
1962
1963 // we need to discard any previously cached images which are elevation aware, so that these will be updated when
1964 // the canvas is redrawn
1965 mCacheInvalidations |= CacheInvalidationType::Elevation;
1966
1967 autoRefreshTriggered();
1968}
1969
1971{
1972 // no selected features, only one selected point feature
1973 //or two point features with the same x- or y-coordinates
1974 if ( rect.isEmpty() || !QgsMapSettingsUtils::isValidExtent( rect ) )
1975 {
1976 // zoom in
1977 QgsPointXY c = rect.center();
1978 rect = extent();
1979 rect.scale( 1.0, &c );
1980 }
1981 //zoom to an area
1982 else
1983 {
1984 // Expand rect to give a bit of space around the selected
1985 // objects so as to keep them clear of the map boundaries
1986 // The same 5% should apply to all margins.
1987 rect.scale( 1.05 );
1988 }
1989
1990 setExtent( rect, true );
1991 refresh();
1992}
1993
1995{
1996 if ( !layer )
1997 {
1998 return;
1999 }
2000
2001 QgsRectangle bbox;
2002 QString errorMsg;
2003 if ( boundingBoxOfFeatureIds( ids, layer, bbox, errorMsg ) )
2004 {
2005 if ( bbox.isEmpty() )
2006 {
2007 bbox = optimalExtentForPointLayer( layer, bbox.center() );
2008 }
2009 zoomToFeatureExtent( bbox );
2010 }
2011 else
2012 {
2013 emit messageEmitted( tr( "Zoom to feature id failed" ), errorMsg, Qgis::MessageLevel::Warning );
2014 }
2015}
2016
2017void QgsMapCanvas::panToFeatureIds( QgsVectorLayer *layer, const QgsFeatureIds &ids, bool alwaysRecenter )
2018{
2019 if ( !layer )
2020 {
2021 return;
2022 }
2023
2024 QgsRectangle bbox;
2025 QString errorMsg;
2026 if ( boundingBoxOfFeatureIds( ids, layer, bbox, errorMsg ) )
2027 {
2028 if ( alwaysRecenter || !mapSettings().extent().contains( bbox ) )
2029 setCenter( bbox.center() );
2030 refresh();
2031 }
2032 else
2033 {
2034 emit messageEmitted( tr( "Pan to feature id failed" ), errorMsg, Qgis::MessageLevel::Warning );
2035 }
2036}
2037
2038bool QgsMapCanvas::boundingBoxOfFeatureIds( const QgsFeatureIds &ids, QgsVectorLayer *layer, QgsRectangle &bbox, QString &errorMsg ) const
2039{
2040 QgsFeatureIterator it = layer->getFeatures( QgsFeatureRequest().setFilterFids( ids ).setNoAttributes() );
2041 bbox.setNull();
2042 QgsFeature fet;
2043 int featureCount = 0;
2044 errorMsg.clear();
2045
2046 while ( it.nextFeature( fet ) )
2047 {
2048 QgsGeometry geom = fet.geometry();
2049 if ( geom.isNull() )
2050 {
2051 errorMsg = tr( "Feature does not have a geometry" );
2052 }
2053 else if ( geom.constGet()->isEmpty() )
2054 {
2055 errorMsg = tr( "Feature geometry is empty" );
2056 }
2057 if ( !errorMsg.isEmpty() )
2058 {
2059 return false;
2060 }
2061 QgsRectangle r = mapSettings().layerExtentToOutputExtent( layer, geom.boundingBox() );
2062 bbox.combineExtentWith( r );
2063 featureCount++;
2064 }
2065
2066 if ( featureCount != ids.count() )
2067 {
2068 errorMsg = tr( "Feature not found" );
2069 return false;
2070 }
2071
2072 return true;
2073}
2074
2076{
2077 if ( !layer )
2078 {
2079 // use current layer by default
2080 layer = mCurrentLayer;
2081 }
2082 if ( !layer || !layer->isSpatial() )
2083 return;
2084
2085 QgsRectangle rect;
2086 switch ( layer->type() )
2087 {
2089 {
2090 QgsVectorLayer *vLayer = qobject_cast<QgsVectorLayer *>( layer );
2091 if ( vLayer->selectedFeatureCount() == 0 )
2092 return;
2093
2094 rect = vLayer->boundingBoxOfSelected();
2095 break;
2096 }
2098 {
2099 QgsVectorTileLayer *vtLayer = qobject_cast<QgsVectorTileLayer *>( layer );
2100 if ( vtLayer->selectedFeatureCount() == 0 )
2101 return;
2102
2103 const QList<QgsFeature> selectedFeatures = vtLayer->selectedFeatures();
2104 for ( const QgsFeature &feature : selectedFeatures )
2105 {
2106 if ( !feature.hasGeometry() )
2107 continue;
2108
2109 rect.combineExtentWith( feature.geometry().boundingBox() );
2110 }
2111 break;
2112 }
2113
2121 return;
2122 }
2123
2124 if ( rect.isNull() )
2125 {
2126 emit messageEmitted( tr( "Cannot pan to selected feature(s)" ), tr( "No extent could be determined." ), Qgis::MessageLevel::Warning );
2127 return;
2128 }
2129
2131 setCenter( rect.center() );
2132 refresh();
2133}
2134
2135void QgsMapCanvas::panToSelected( const QList<QgsMapLayer *> &layers )
2136{
2137 QgsRectangle selectionExtent;
2138 selectionExtent.setNull();
2139
2140 for ( QgsMapLayer *mapLayer : layers )
2141 {
2142 if ( !mapLayer || !mapLayer->isSpatial() )
2143 continue;
2144
2145 QgsRectangle rect;
2146 switch ( mapLayer->type() )
2147 {
2149 {
2150 QgsVectorLayer *layer = qobject_cast<QgsVectorLayer *>( mapLayer );
2151 if ( layer->selectedFeatureCount() == 0 )
2152 continue;
2153
2154 rect = layer->boundingBoxOfSelected();
2155
2156 if ( rect.isNull() )
2157 continue;
2158
2160
2161 if ( layer->geometryType() == Qgis::GeometryType::Point && rect.isEmpty() )
2162 rect = optimalExtentForPointLayer( layer, rect.center() );
2163 break;
2164 }
2165
2167 {
2168 QgsVectorTileLayer *vtLayer = qobject_cast<QgsVectorTileLayer *>( mapLayer );
2169 if ( vtLayer->selectedFeatureCount() == 0 )
2170 continue;
2171
2172 const QList<QgsFeature> selectedFeatures = vtLayer->selectedFeatures();
2173 for ( const QgsFeature &feature : selectedFeatures )
2174 {
2175 if ( !feature.hasGeometry() )
2176 continue;
2177
2178 rect.combineExtentWith( feature.geometry().boundingBox() );
2179 }
2180
2181 rect = mapSettings().layerExtentToOutputExtent( vtLayer, rect );
2182 break;
2183 }
2184
2192 continue;
2193 }
2194
2195 selectionExtent.combineExtentWith( rect );
2196 }
2197
2198 if ( selectionExtent.isNull() )
2199 {
2200 emit messageEmitted( tr( "Cannot pan to selected feature(s)" ), tr( "No extent could be determined." ), Qgis::MessageLevel::Warning );
2201 return;
2202 }
2203
2204 setCenter( selectionExtent.center() );
2205 refresh();
2206}
2207
2208void QgsMapCanvas::flashFeatureIds( QgsVectorLayer *layer, const QgsFeatureIds &ids, const QColor &color1, const QColor &color2, int flashes, int duration )
2209{
2210 if ( !layer )
2211 {
2212 return;
2213 }
2214
2215 QList<QgsGeometry> geoms;
2216
2217 QgsFeatureIterator it = layer->getFeatures( QgsFeatureRequest().setFilterFids( ids ).setNoAttributes() );
2218 QgsFeature fet;
2219 while ( it.nextFeature( fet ) )
2220 {
2221 if ( !fet.hasGeometry() )
2222 continue;
2223 geoms << fet.geometry();
2224 }
2225
2226 flashGeometries( geoms, layer->crs(), color1, color2, flashes, duration );
2227}
2228
2229void QgsMapCanvas::flashGeometries( const QList<QgsGeometry> &geometries, const QgsCoordinateReferenceSystem &crs, const QColor &color1, const QColor &color2, int flashes, int duration )
2230{
2231 if ( geometries.isEmpty() )
2232 return;
2233
2234 Qgis::GeometryType geomType = QgsWkbTypes::geometryType( geometries.at( 0 ).wkbType() );
2235 QgsRubberBand *rb = new QgsRubberBand( this, geomType );
2236 for ( const QgsGeometry &geom : geometries )
2237 rb->addGeometry( geom, crs, false );
2238 rb->updatePosition();
2239 rb->update();
2240
2241 if ( geomType == Qgis::GeometryType::Line || geomType == Qgis::GeometryType::Point )
2242 {
2243 rb->setWidth( 2 );
2244 rb->setSecondaryStrokeColor( QColor( 255, 255, 255 ) );
2245 }
2246 if ( geomType == Qgis::GeometryType::Point )
2248
2249 QColor startColor = color1;
2250 if ( !startColor.isValid() )
2251 {
2252 if ( geomType == Qgis::GeometryType::Polygon )
2253 {
2254 startColor = rb->fillColor();
2255 }
2256 else
2257 {
2258 startColor = rb->strokeColor();
2259 }
2260 startColor.setAlpha( 255 );
2261 }
2262 QColor endColor = color2;
2263 if ( !endColor.isValid() )
2264 {
2265 endColor = startColor;
2266 endColor.setAlpha( 0 );
2267 }
2268
2269
2270 QVariantAnimation *animation = new QVariantAnimation( this );
2271 connect( animation, &QVariantAnimation::finished, this, [animation, rb] {
2272 animation->deleteLater();
2273 delete rb;
2274 } );
2275 connect( animation, &QPropertyAnimation::valueChanged, this, [rb, geomType]( const QVariant &value ) {
2276 QColor c = value.value<QColor>();
2277 if ( geomType == Qgis::GeometryType::Polygon )
2278 {
2279 rb->setFillColor( c );
2280 }
2281 else
2282 {
2283 rb->setStrokeColor( c );
2284 QColor c = rb->secondaryStrokeColor();
2285 c.setAlpha( c.alpha() );
2287 }
2288 rb->update();
2289 } );
2290
2291 animation->setDuration( duration * flashes );
2292 animation->setStartValue( endColor );
2293 double midStep = 0.2 / flashes;
2294 for ( int i = 0; i < flashes; ++i )
2295 {
2296 double start = static_cast<double>( i ) / flashes;
2297 animation->setKeyValueAt( start + midStep, startColor );
2298 double end = static_cast<double>( i + 1 ) / flashes;
2299 if ( !qgsDoubleNear( end, 1.0 ) )
2300 animation->setKeyValueAt( end, endColor );
2301 }
2302 animation->setEndValue( endColor );
2303 animation->start();
2304}
2305
2307{
2308 if ( mCanvasProperties->mouseButtonDown || mCanvasProperties->panSelectorDown )
2309 {
2310 emit keyPressed( e );
2311 return;
2312 }
2313
2314 // Don't want to interfer with mouse events
2315 if ( !mCanvasProperties->mouseButtonDown )
2316 {
2317 // this is backwards, but we can't change now without breaking api because
2318 // forever QgsMapTools have had to explicitly mark events as ignored in order to
2319 // indicate that they've consumed the event and that the default behavior should not
2320 // be applied..!
2321 e->accept();
2322 if ( mMapTool )
2323 {
2324 mMapTool->keyPressEvent( e );
2325 if ( !e->isAccepted() ) // map tool consumed event
2326 return;
2327 }
2328
2329 QgsRectangle currentExtent = mapSettings().visibleExtent();
2330 double dx = std::fabs( currentExtent.width() / 4 );
2331 double dy = std::fabs( currentExtent.height() / 4 );
2332
2333 switch ( e->key() )
2334 {
2335 case Qt::Key_Left:
2336 QgsDebugMsgLevel( u"Pan left"_s, 2 );
2337 setCenter( center() - QgsVector( dx, 0 ).rotateBy( rotation() * M_PI / 180.0 ) );
2338 refresh();
2339 break;
2340
2341 case Qt::Key_Right:
2342 QgsDebugMsgLevel( u"Pan right"_s, 2 );
2343 setCenter( center() + QgsVector( dx, 0 ).rotateBy( rotation() * M_PI / 180.0 ) );
2344 refresh();
2345 break;
2346
2347 case Qt::Key_Up:
2348 QgsDebugMsgLevel( u"Pan up"_s, 2 );
2349 setCenter( center() + QgsVector( 0, dy ).rotateBy( rotation() * M_PI / 180.0 ) );
2350 refresh();
2351 break;
2352
2353 case Qt::Key_Down:
2354 QgsDebugMsgLevel( u"Pan down"_s, 2 );
2355 setCenter( center() - QgsVector( 0, dy ).rotateBy( rotation() * M_PI / 180.0 ) );
2356 refresh();
2357 break;
2358
2359 case Qt::Key_Space:
2360 QgsDebugMsgLevel( u"Pressing pan selector"_s, 2 );
2361
2362 //mCanvasProperties->dragging = true;
2363 if ( !e->isAutoRepeat() )
2364 {
2365 mTemporaryCursorOverride = std::make_unique<QgsTemporaryCursorOverride>( Qt::ClosedHandCursor );
2366 mCanvasProperties->panSelectorDown = true;
2367 panActionStart( mCanvasProperties->mouseLastXY );
2368 }
2369 break;
2370
2371 case Qt::Key_PageUp:
2372 QgsDebugMsgLevel( u"Zoom in"_s, 2 );
2373 zoomIn();
2374 break;
2375
2376 case Qt::Key_PageDown:
2377 QgsDebugMsgLevel( u"Zoom out"_s, 2 );
2378 zoomOut();
2379 break;
2380
2381#if 0
2382 case Qt::Key_P:
2383 mUseParallelRendering = !mUseParallelRendering;
2384 refresh();
2385 break;
2386
2387 case Qt::Key_S:
2388 mDrawRenderingStats = !mDrawRenderingStats;
2389 refresh();
2390 break;
2391#endif
2392
2393 default:
2394 // Pass it on
2395 if ( !mMapTool )
2396 {
2397 e->ignore();
2398 QgsDebugMsgLevel( "Ignoring key: " + QString::number( e->key() ), 2 );
2399 }
2400 }
2401 }
2402
2403 emit keyPressed( e );
2404}
2405
2407{
2408 QgsDebugMsgLevel( u"keyRelease event"_s, 2 );
2409
2410 switch ( e->key() )
2411 {
2412 case Qt::Key_Space:
2413 if ( !e->isAutoRepeat() && mCanvasProperties->panSelectorDown )
2414 {
2415 QgsDebugMsgLevel( u"Releasing pan selector"_s, 2 );
2416 mTemporaryCursorOverride.reset();
2417 mCanvasProperties->panSelectorDown = false;
2418 panActionEnd( mCanvasProperties->mouseLastXY );
2419 }
2420 break;
2421
2422 default:
2423 // Pass it on
2424 if ( mMapTool )
2425 {
2426 mMapTool->keyReleaseEvent( e );
2427 }
2428 else
2429 e->ignore();
2430
2431 QgsDebugMsgLevel( "Ignoring key release: " + QString::number( e->key() ), 2 );
2432 }
2433
2434 emit keyReleased( e );
2435
2436} //keyReleaseEvent()
2437
2438
2440{
2441 // call handler of current map tool
2442 if ( mMapTool )
2443 {
2444 auto me = std::make_unique<QgsMapMouseEvent>( this, e );
2445 mMapTool->canvasDoubleClickEvent( me.get() );
2446 }
2447} // mouseDoubleClickEvent
2448
2449
2450void QgsMapCanvas::beginZoomRect( QPoint pos )
2451{
2452 mZoomRect.setRect( 0, 0, 0, 0 );
2453 mTemporaryCursorOverride = std::make_unique<QgsTemporaryCursorOverride>( mZoomCursor );
2454 mZoomDragging = true;
2455 mZoomRubberBand = std::make_unique<QgsRubberBand>( this, Qgis::GeometryType::Polygon );
2456 QColor color( Qt::blue );
2457 color.setAlpha( 63 );
2458 mZoomRubberBand->setColor( color );
2459 mZoomRect.setTopLeft( pos );
2460}
2461
2462void QgsMapCanvas::stopZoomRect()
2463{
2464 if ( mZoomDragging )
2465 {
2466 mZoomDragging = false;
2467 mZoomRubberBand.reset( nullptr );
2468 mTemporaryCursorOverride.reset();
2469 }
2470}
2471
2472void QgsMapCanvas::endZoomRect( QPoint pos )
2473{
2474 stopZoomRect();
2475
2476 // store the rectangle
2477 mZoomRect.setRight( pos.x() );
2478 mZoomRect.setBottom( pos.y() );
2479
2480 //account for bottom right -> top left dragging
2481 mZoomRect = mZoomRect.normalized();
2482
2483 if ( mZoomRect.width() < 5 && mZoomRect.height() < 5 )
2484 {
2485 //probably a mistake - would result in huge zoom!
2486 return;
2487 }
2488
2489 // set center and zoom
2490 const QSize &zoomRectSize = mZoomRect.size();
2491 const QSize &canvasSize = mSettings.outputSize();
2492 double sfx = static_cast<double>( zoomRectSize.width() ) / canvasSize.width();
2493 double sfy = static_cast<double>( zoomRectSize.height() ) / canvasSize.height();
2494 double sf = std::max( sfx, sfy );
2495
2496 QgsPointXY c = mSettings.mapToPixel().toMapCoordinates( mZoomRect.center() );
2497
2498 zoomByFactor( sf, &c );
2499 refresh();
2500}
2501
2502void QgsMapCanvas::startPan()
2503{
2504 if ( !mCanvasProperties->panSelectorDown )
2505 {
2506 mCanvasProperties->panSelectorDown = true;
2507 mTemporaryCursorOverride = std::make_unique<QgsTemporaryCursorOverride>( Qt::ClosedHandCursor );
2508 panActionStart( mCanvasProperties->mouseLastXY );
2509 }
2510}
2511
2512void QgsMapCanvas::stopPan()
2513{
2514 if ( mCanvasProperties->panSelectorDown )
2515 {
2516 mCanvasProperties->panSelectorDown = false;
2517 mTemporaryCursorOverride.reset();
2518 panActionEnd( mCanvasProperties->mouseLastXY );
2519 }
2520}
2521
2522void QgsMapCanvas::mousePressEvent( QMouseEvent *e )
2523{
2524 // use shift+middle mouse button for zooming, map tools won't receive any events in that case
2525 if ( e->button() == Qt::MiddleButton && e->modifiers() & Qt::ShiftModifier )
2526 {
2527 beginZoomRect( e->pos() );
2528 return;
2529 }
2530 //use middle mouse button for panning, map tools won't receive any events in that case
2531 else if ( e->button() == Qt::MiddleButton )
2532 {
2533 startPan();
2534 }
2535 else
2536 {
2537 // If doing a middle-button-click, followed by a right-button-click,
2538 // cancel the pan or zoomRect action started above.
2539 stopPan();
2540 stopZoomRect();
2541
2542 // call handler of current map tool
2543 if ( mMapTool )
2544 {
2545 if ( mMapTool->flags() & QgsMapTool::AllowZoomRect && e->button() == Qt::LeftButton && e->modifiers() & Qt::ShiftModifier )
2546 {
2547 beginZoomRect( e->pos() );
2548 return;
2549 }
2550 else if ( mMapTool->flags() & QgsMapTool::ShowContextMenu && e->button() == Qt::RightButton )
2551 {
2552 auto me = std::make_unique<QgsMapMouseEvent>( this, e );
2553 showContextMenu( me.get() );
2554 return;
2555 }
2556 else
2557 {
2558 auto me = std::make_unique<QgsMapMouseEvent>( this, e );
2559 mMapTool->canvasPressEvent( me.get() );
2560 }
2561 }
2562 }
2563
2564 if ( mCanvasProperties->panSelectorDown )
2565 {
2566 return;
2567 }
2568
2569 mCanvasProperties->mouseButtonDown = true;
2570 mCanvasProperties->rubberStartPoint = e->pos();
2571}
2572
2574{
2575 // if using shift+middle mouse button for zooming, end zooming and return
2576 if ( mZoomDragging && e->button() == Qt::MiddleButton )
2577 {
2578 endZoomRect( e->pos() );
2579 return;
2580 }
2581 //use middle mouse button for panning, map tools won't receive any events in that case
2582 else if ( e->button() == Qt::MiddleButton )
2583 {
2584 stopPan();
2585 }
2586 else if ( e->button() == Qt::BackButton )
2587 {
2589 return;
2590 }
2591 else if ( e->button() == Qt::ForwardButton )
2592 {
2594 return;
2595 }
2596 else
2597 {
2598 if ( mZoomDragging && e->button() == Qt::LeftButton )
2599 {
2600 endZoomRect( e->pos() );
2601 return;
2602 }
2603
2604 // call handler of current map tool
2605 if ( mMapTool )
2606 {
2607 auto me = std::make_unique<QgsMapMouseEvent>( this, e );
2608 mMapTool->canvasReleaseEvent( me.get() );
2609 }
2610 }
2611
2612
2613 mCanvasProperties->mouseButtonDown = false;
2614
2615 if ( mCanvasProperties->panSelectorDown )
2616 return;
2617}
2618
2619void QgsMapCanvas::resizeEvent( QResizeEvent *e )
2620{
2621 QGraphicsView::resizeEvent( e );
2622 mResizeTimer->start( 500 ); // in charge of refreshing canvas
2623
2624 double oldScale = mSettings.scale();
2625 QSize lastSize = viewport()->size();
2626 mSettings.setOutputSize( lastSize );
2627
2628 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
2629
2630 moveCanvasContents( true );
2631
2632 if ( mScaleLocked )
2633 {
2634 double scaleFactor = oldScale / mSettings.scale();
2635 QgsRectangle r = mSettings.extent();
2636 QgsPointXY center = r.center();
2637 r.scale( scaleFactor, &center );
2638 mSettings.setExtent( r );
2639 }
2640 else
2641 {
2642 updateScale();
2643 }
2644
2646}
2647
2648void QgsMapCanvas::paintEvent( QPaintEvent *e )
2649{
2650 // no custom event handling anymore
2651
2652 QGraphicsView::paintEvent( e );
2653} // paintEvent
2654
2656{
2657 if ( mBlockItemPositionUpdates )
2658 return;
2659
2660 const QList<QGraphicsItem *> items = mScene->items();
2661 for ( QGraphicsItem *gi : items )
2662 {
2663 QgsMapCanvasItem *item = dynamic_cast<QgsMapCanvasItem *>( gi );
2664
2665 if ( item )
2666 {
2667 item->updatePosition();
2668 }
2669 }
2670}
2671
2672
2673void QgsMapCanvas::wheelEvent( QWheelEvent *e )
2674{
2675 // Zoom the map canvas in response to a mouse wheel event. Moving the
2676 // wheel forward (away) from the user zooms in
2677
2678 QgsDebugMsgLevel( "Wheel event delta " + QString::number( e->angleDelta().y() ), 2 );
2679
2680 if ( mMapTool )
2681 {
2682 mMapTool->wheelEvent( e );
2683 if ( e->isAccepted() )
2684 return;
2685 }
2686
2687 if ( e->angleDelta().y() == 0 )
2688 {
2689 e->accept();
2690 return;
2691 }
2692
2693 bool reverseZoom = QgsSettingsRegistryGui::settingsReverseWheelZoom->value();
2694 bool zoomIn = reverseZoom ? e->angleDelta().y() < 0 : e->angleDelta().y() > 0;
2695 double zoomFactor = zoomIn ? 1. / zoomInFactor() : zoomOutFactor();
2696
2697 // "Normal" mouse have an angle delta of 120, precision mouses provide data faster, in smaller steps
2698 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( e->angleDelta().y() );
2699
2700 if ( e->modifiers() & Qt::ControlModifier )
2701 {
2702 //holding ctrl while wheel zooming results in a finer zoom
2703 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
2704 }
2705
2706 double signedWheelFactor = zoomIn ? 1 / zoomFactor : zoomFactor;
2707
2708 // zoom map to mouse cursor by scaling
2709 QgsPointXY oldCenter = center();
2710 QgsPointXY mousePos( getCoordinateTransform()->toMapCoordinates( e->position().x(), e->position().y() ) );
2711 QgsPointXY newCenter( mousePos.x() + ( ( oldCenter.x() - mousePos.x() ) * signedWheelFactor ), mousePos.y() + ( ( oldCenter.y() - mousePos.y() ) * signedWheelFactor ) );
2712
2713 zoomByFactor( signedWheelFactor, &newCenter );
2714 e->accept();
2715}
2716
2717void QgsMapCanvas::setWheelFactor( double factor )
2718{
2719 mWheelZoomFactor = std::max( factor, 1.01 );
2720}
2721
2723{
2724 // magnification is already handled in zoomByFactor
2726}
2727
2729{
2730 // magnification is already handled in zoomByFactor
2732}
2733
2734void QgsMapCanvas::zoomScale( double newScale, bool ignoreScaleLock )
2735{
2736 zoomByFactor( newScale / scale(), nullptr, ignoreScaleLock );
2737}
2738
2739void QgsMapCanvas::zoomWithCenter( int x, int y, bool zoomIn )
2740{
2741 double scaleFactor = ( zoomIn ? zoomInFactor() : zoomOutFactor() );
2742
2743 // transform the mouse pos to map coordinates
2745
2746 if ( mScaleLocked )
2747 {
2748 ScaleRestorer restorer( this );
2750 }
2751 else
2752 {
2753 zoomByFactor( scaleFactor, &center );
2754 }
2755}
2756
2757void QgsMapCanvas::setScaleLocked( bool isLocked )
2758{
2759 if ( mScaleLocked != isLocked )
2760 {
2761 mScaleLocked = isLocked;
2762 emit scaleLockChanged( mScaleLocked );
2763 }
2764}
2765
2766void QgsMapCanvas::mouseMoveEvent( QMouseEvent *e )
2767{
2768 mCanvasProperties->mouseLastXY = e->pos();
2769
2770 if ( mCanvasProperties->panSelectorDown )
2771 {
2772 panAction( e );
2773 }
2774 else if ( mZoomDragging )
2775 {
2776 mZoomRect.setBottomRight( e->pos() );
2777 mZoomRubberBand->setToCanvasRectangle( mZoomRect );
2778 mZoomRubberBand->show();
2779 }
2780 else
2781 {
2782 // call handler of current map tool
2783 if ( mMapTool )
2784 {
2785 auto me = std::make_unique<QgsMapMouseEvent>( this, e );
2786 mMapTool->canvasMoveEvent( me.get() );
2787 }
2788 }
2789
2790 // show x y on status bar (if we are mid pan operation, then the cursor point hasn't changed!)
2791 if ( !panOperationInProgress() )
2792 {
2793 mCursorPoint = getCoordinateTransform()->toMapCoordinates( mCanvasProperties->mouseLastXY );
2794 emit xyCoordinates( mCursorPoint );
2795 }
2796}
2797
2798void QgsMapCanvas::setMapTool( QgsMapTool *tool, bool clean )
2799{
2800 if ( !tool )
2801 return;
2802
2803 if ( tool == mMapTool )
2804 {
2805 mMapTool->reactivate();
2806 return;
2807 }
2808
2809 if ( mMapTool )
2810 {
2811 if ( clean )
2812 mMapTool->clean();
2813
2814 disconnect( mMapTool, &QObject::destroyed, this, &QgsMapCanvas::mapToolDestroyed );
2815 mMapTool->deactivate();
2816 }
2817
2818 QgsMapTool *oldTool = mMapTool;
2819
2820 // set new map tool and activate it
2821 mMapTool = tool;
2822 emit mapToolSet( mMapTool, oldTool );
2823 if ( mMapTool )
2824 {
2825 connect( mMapTool, &QObject::destroyed, this, &QgsMapCanvas::mapToolDestroyed );
2826 mMapTool->activate();
2827 }
2828
2829} // setMapTool
2830
2832{
2833 if ( mMapTool && mMapTool == tool )
2834 {
2835 disconnect( mMapTool, &QObject::destroyed, this, &QgsMapCanvas::mapToolDestroyed );
2836 QgsMapTool *oldTool = mMapTool;
2837 mMapTool = nullptr;
2838 oldTool->deactivate();
2839 emit mapToolSet( nullptr, oldTool );
2840 setCursor( Qt::ArrowCursor );
2841 }
2842}
2843
2845{
2846 if ( mProject )
2847 disconnect( mProject, &QgsProject::elevationShadingRendererChanged, this, &QgsMapCanvas::onElevationShadingRendererChanged );
2848
2849 mProject = project;
2850
2851 if ( mProject )
2852 connect( mProject, &QgsProject::elevationShadingRendererChanged, this, &QgsMapCanvas::onElevationShadingRendererChanged );
2853}
2854
2855void QgsMapCanvas::setCanvasColor( const QColor &color )
2856{
2857 if ( canvasColor() == color )
2858 return;
2859
2860 // background of map's pixmap
2861 mSettings.setBackgroundColor( color );
2862
2863 // background of the QGraphicsView
2864 QBrush bgBrush( color );
2865 setBackgroundBrush( bgBrush );
2866#if 0
2867 QPalette palette;
2868 palette.setColor( backgroundRole(), color );
2869 setPalette( palette );
2870#endif
2871
2872 // background of QGraphicsScene
2873 mScene->setBackgroundBrush( bgBrush );
2874
2875 refresh();
2876
2877 emit canvasColorChanged();
2878}
2879
2881{
2882 return mScene->backgroundBrush().color();
2883}
2884
2885void QgsMapCanvas::setSelectionColor( const QColor &color )
2886{
2887 if ( mSettings.selectionColor() == color )
2888 return;
2889
2890 mSettings.setSelectionColor( color );
2891
2892 if ( mCache )
2893 {
2894 bool hasSelectedFeatures = false;
2895 const auto layers = mSettings.layers();
2896 for ( QgsMapLayer *layer : layers )
2897 {
2898 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
2899 if ( vlayer && vlayer->selectedFeatureCount() )
2900 {
2901 hasSelectedFeatures = true;
2902 break;
2903 }
2904 }
2905
2906 if ( hasSelectedFeatures )
2907 {
2908 mCache->clear();
2909 refresh();
2910 }
2911 }
2912}
2913
2915{
2916 return mSettings.selectionColor();
2917}
2918
2920{
2921 return mapSettings().layers().size();
2922}
2923
2924QList<QgsMapLayer *> QgsMapCanvas::layers( bool expandGroupLayers ) const
2925{
2926 return mapSettings().layers( expandGroupLayers );
2927}
2928
2930{
2931 // called when a layer has changed visibility setting
2932 refresh();
2933}
2934
2935void QgsMapCanvas::freeze( bool frozen )
2936{
2937 mFrozen = frozen;
2938}
2939
2941{
2942 return mFrozen;
2943}
2944
2946{
2947 return mapSettings().mapUnitsPerPixel();
2948}
2949
2954
2955QMap<QString, QString> QgsMapCanvas::layerStyleOverrides() const
2956{
2957 return mSettings.layerStyleOverrides();
2958}
2959
2960void QgsMapCanvas::setLayerStyleOverrides( const QMap<QString, QString> &overrides )
2961{
2962 if ( overrides == mSettings.layerStyleOverrides() )
2963 return;
2964
2965 mSettings.setLayerStyleOverrides( overrides );
2966 clearCache();
2968}
2969
2970void QgsMapCanvas::setTheme( const QString &theme )
2971{
2972 if ( mTheme == theme )
2973 return;
2974
2975 clearCache();
2976 if ( theme.isEmpty() || !QgsProject::instance()->mapThemeCollection()->hasMapTheme( theme ) )
2977 {
2978 mTheme.clear();
2979 mSettings.setLayerStyleOverrides( QMap<QString, QString>() );
2980 setLayers( QgsProject::instance()->mapThemeCollection()->masterVisibleLayers() );
2981 emit themeChanged( QString() );
2982 }
2983 else
2984 {
2985 mTheme = theme;
2986 setLayersPrivate( QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
2987 emit themeChanged( theme );
2988 }
2989}
2990
2992{
2993 mRenderFlag = flag;
2994
2995 if ( mRenderFlag )
2996 {
2997 refresh();
2998 }
2999 else
3000 stopRendering();
3001}
3002
3003#if 0
3004void QgsMapCanvas::connectNotify( const char *signal )
3005{
3006 Q_UNUSED( signal )
3007 QgsDebugMsgLevel( "QgsMapCanvas connected to " + QString( signal ), 2 );
3008} //connectNotify
3009#endif
3010
3011void QgsMapCanvas::layerRepaintRequested( bool deferred )
3012{
3013 if ( !deferred )
3014 refresh();
3015}
3016
3017void QgsMapCanvas::autoRefreshTriggered()
3018{
3019 if ( mJob )
3020 {
3021 // canvas is currently being redrawn, so we defer the last requested
3022 // auto refresh until current rendering job finishes
3023 mRefreshAfterJob = true;
3024 return;
3025 }
3026
3027 refresh();
3028}
3029
3030void QgsMapCanvas::updateAutoRefreshTimer()
3031{
3032 // min auto refresh interval stores the smallest interval between layer auto refreshes. We automatically
3033 // trigger a map refresh on this minimum interval
3034 int minAutoRefreshInterval = -1;
3035 const auto layers = mSettings.layers();
3036 for ( QgsMapLayer *layer : layers )
3037 {
3038 int layerRefreshInterval = 0;
3039
3040 if ( layer->hasAutoRefreshEnabled() && layer->autoRefreshInterval() > 0 )
3041 {
3042 layerRefreshInterval = layer->autoRefreshInterval();
3043 }
3044 else if ( QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>( layer ) )
3045 {
3046 if ( const QgsFeatureRenderer *renderer = vectorLayer->renderer() )
3047 {
3048 const double rendererRefreshRate = QgsSymbolLayerUtils::rendererFrameRate( renderer );
3049 if ( rendererRefreshRate > 0 )
3050 {
3051 layerRefreshInterval = 1000 / rendererRefreshRate;
3052 }
3053 }
3054 }
3055
3056 if ( layerRefreshInterval == 0 )
3057 continue;
3058
3059 minAutoRefreshInterval = minAutoRefreshInterval > 0 ? std::min( layerRefreshInterval, minAutoRefreshInterval ) : layerRefreshInterval;
3060 }
3061
3062 if ( minAutoRefreshInterval > 0 )
3063 {
3064 mAutoRefreshTimer.setInterval( minAutoRefreshInterval );
3065 mAutoRefreshTimer.start();
3066 }
3067 else
3068 {
3069 mAutoRefreshTimer.stop();
3070 }
3071}
3072
3073void QgsMapCanvas::projectThemesChanged()
3074{
3075 if ( mTheme.isEmpty() )
3076 return;
3077
3078 if ( !QgsProject::instance()->mapThemeCollection()->hasMapTheme( mTheme ) )
3079 {
3080 // theme has been removed - stop following
3081 setTheme( QString() );
3082 }
3083}
3084
3086{
3087 return mMapTool;
3088}
3089
3091{
3092 return mProject;
3093}
3094
3095void QgsMapCanvas::panActionEnd( QPoint releasePoint )
3096{
3097 // move map image and other items to standard position
3098 moveCanvasContents( true ); // true means reset
3099
3100 // use start and end box points to calculate the extent
3102 QgsPointXY end = getCoordinateTransform()->toMapCoordinates( releasePoint );
3103
3104 // modify the center
3105 double dx = end.x() - start.x();
3106 double dy = end.y() - start.y();
3107 QgsPointXY c = center();
3108 c.set( c.x() - dx, c.y() - dy );
3109 setCenter( c );
3110
3111 refresh();
3112}
3113
3114void QgsMapCanvas::panActionStart( QPoint releasePoint )
3115{
3116 mCanvasProperties->rubberStartPoint = releasePoint;
3117
3118 mDa = QgsDistanceArea();
3119 mDa.setEllipsoid( QgsProject::instance()->ellipsoid() );
3120 mDa.setSourceCrs( mapSettings().destinationCrs(), QgsProject::instance()->transformContext() );
3121}
3122
3123void QgsMapCanvas::panAction( QMouseEvent *e )
3124{
3125 Q_UNUSED( e )
3126
3127 QgsPointXY currentMapPoint = getCoordinateTransform()->toMapCoordinates( e->pos() );
3128 QgsPointXY startMapPoint = getCoordinateTransform()->toMapCoordinates( mCanvasProperties->rubberStartPoint );
3129 try
3130 {
3131 emit panDistanceBearingChanged( mDa.measureLine( currentMapPoint, startMapPoint ), mDa.lengthUnits(), mDa.bearing( currentMapPoint, startMapPoint ) * 180 / M_PI );
3132 }
3133 catch ( QgsCsException & )
3134 {}
3135
3136 // move all map canvas items
3138}
3139
3141{
3142 QPoint pnt( 0, 0 );
3143 if ( !reset )
3144 pnt += mCanvasProperties->mouseLastXY - mCanvasProperties->rubberStartPoint;
3145
3146 setSceneRect( -pnt.x(), -pnt.y(), viewport()->size().width(), viewport()->size().height() );
3147}
3148
3150{
3151 if ( QgsMimeDataUtils::isUriList( event->mimeData() ) )
3152 {
3154 bool allHandled = true;
3155 for ( const QgsMimeDataUtils::Uri &uri : lst )
3156 {
3157 bool handled = false;
3158 for ( QgsCustomDropHandler *handler : std::as_const( mDropHandlers ) )
3159 {
3160 if ( handler && handler->customUriProviderKey() == uri.providerKey )
3161 {
3162 if ( handler->handleCustomUriCanvasDrop( uri, this ) )
3163 {
3164 handled = true;
3165 break;
3166 }
3167 }
3168 }
3169 if ( !handled )
3170 allHandled = false;
3171 }
3172 if ( allHandled )
3173 event->accept();
3174 else
3175 event->ignore();
3176 }
3177 else
3178 {
3179 event->ignore();
3180 }
3181}
3182
3184{
3185 Q_UNUSED( event )
3186 updateDevicePixelFromScreen();
3187}
3188
3190{
3191 if ( !mBlockExtentChangedSignal )
3192 emit extentsChanged();
3193}
3194
3196{
3197 return mCanvasProperties->mouseLastXY;
3198}
3199
3200void QgsMapCanvas::setPreviewModeEnabled( bool previewEnabled )
3201{
3202 if ( !mPreviewEffect )
3203 {
3204 return;
3205 }
3206
3207 mPreviewEffect->setEnabled( previewEnabled );
3208}
3209
3211{
3212 if ( !mPreviewEffect )
3213 {
3214 return false;
3215 }
3216
3217 return mPreviewEffect->isEnabled();
3218}
3219
3221{
3222 if ( !mPreviewEffect )
3223 {
3224 return;
3225 }
3226
3227 mPreviewEffect->setMode( mode );
3228}
3229
3231{
3232 if ( !mPreviewEffect )
3233 {
3235 }
3236
3237 return mPreviewEffect->mode();
3238}
3239
3241{
3242 if ( !mSnappingUtils )
3243 {
3244 // associate a dummy instance, but better than null pointer
3245 QgsMapCanvas *c = const_cast<QgsMapCanvas *>( this );
3246 c->mSnappingUtils = new QgsMapCanvasSnappingUtils( c, c );
3247 }
3248 return mSnappingUtils;
3249}
3250
3252{
3253 mSnappingUtils = utils;
3254}
3255
3256void QgsMapCanvas::readProject( const QDomDocument &doc )
3257{
3258 QgsProject *project = qobject_cast<QgsProject *>( sender() );
3259
3260 QDomNodeList nodes = doc.elementsByTagName( u"mapcanvas"_s );
3261 if ( nodes.count() )
3262 {
3263 QDomNode node = nodes.item( 0 );
3264
3265 // Search the specific MapCanvas node using the name
3266 if ( nodes.count() > 1 )
3267 {
3268 for ( int i = 0; i < nodes.size(); ++i )
3269 {
3270 QDomElement elementNode = nodes.at( i ).toElement();
3271
3272 if ( elementNode.hasAttribute( u"name"_s ) && elementNode.attribute( u"name"_s ) == objectName() )
3273 {
3274 node = nodes.at( i );
3275 break;
3276 }
3277 }
3278 }
3279
3280 QgsMapSettings tmpSettings;
3281 tmpSettings.readXml( node );
3282 if ( objectName() != "theMapCanvas"_L1 )
3283 {
3284 // never manually set the crs for the main canvas - this is instead connected to the project CRS
3285 setDestinationCrs( tmpSettings.destinationCrs() );
3286 }
3287 if ( QgsProject::instance()->viewSettings()->restoreProjectExtentOnProjectLoad() && objectName() == "theMapCanvas"_L1 )
3288 {
3290 }
3291 else
3292 {
3293 setExtent( tmpSettings.extent() );
3294 }
3295 setRotation( tmpSettings.rotation() );
3297
3298 clearExtentHistory(); // clear the extent history on project load
3299
3300 QDomElement elem = node.toElement();
3301 if ( elem.hasAttribute( u"theme"_s ) )
3302 {
3303 if ( QgsProject::instance()->mapThemeCollection()->hasMapTheme( elem.attribute( u"theme"_s ) ) )
3304 {
3305 setTheme( elem.attribute( u"theme"_s ) );
3306 }
3307 }
3308 setAnnotationsVisible( elem.attribute( u"annotationsVisible"_s, u"1"_s ).toInt() );
3309
3310 // restore canvas expression context
3311 const QDomNodeList scopeElements = elem.elementsByTagName( u"expressionContextScope"_s );
3312 if ( scopeElements.size() > 0 )
3313 {
3314 const QDomElement scopeElement = scopeElements.at( 0 ).toElement();
3315 mExpressionContextScope.readXml( scopeElement, QgsReadWriteContext() );
3316 }
3317 }
3318 else
3319 {
3320 QgsDebugMsgLevel( u"Couldn't read mapcanvas information from project"_s, 2 );
3321 if ( !project->viewSettings()->defaultViewExtent().isNull() )
3322 {
3323 setReferencedExtent( project->viewSettings()->defaultViewExtent() );
3324 }
3325
3326 setRotation( project->viewSettings()->defaultRotation() );
3327 clearExtentHistory(); // clear the extent history on project load
3328 }
3329}
3330
3331void QgsMapCanvas::writeProject( QDomDocument &doc )
3332{
3333 // create node "mapcanvas" and call mMapRenderer->writeXml()
3334
3335 QDomNodeList nl = doc.elementsByTagName( u"qgis"_s );
3336 if ( !nl.count() )
3337 {
3338 QgsDebugError( u"Unable to find qgis element in project file"_s );
3339 return;
3340 }
3341 QDomNode qgisNode = nl.item( 0 ); // there should only be one, so zeroth element OK
3342
3343 QDomElement mapcanvasNode = doc.createElement( u"mapcanvas"_s );
3344 mapcanvasNode.setAttribute( u"name"_s, objectName() );
3345 if ( !mTheme.isEmpty() )
3346 mapcanvasNode.setAttribute( u"theme"_s, mTheme );
3347 mapcanvasNode.setAttribute( u"annotationsVisible"_s, mAnnotationsVisible );
3348 qgisNode.appendChild( mapcanvasNode );
3349
3350 mSettings.writeXml( mapcanvasNode, doc );
3351
3352 // store canvas expression context
3353 QDomElement scopeElement = doc.createElement( u"expressionContextScope"_s );
3354 QgsExpressionContextScope tmpScope( mExpressionContextScope );
3355 tmpScope.removeVariable( u"atlas_featurenumber"_s );
3356 tmpScope.removeVariable( u"atlas_pagename"_s );
3357 tmpScope.removeVariable( u"atlas_feature"_s );
3358 tmpScope.removeVariable( u"atlas_featureid"_s );
3359 tmpScope.removeVariable( u"atlas_geometry"_s );
3360 tmpScope.writeXml( scopeElement, doc, QgsReadWriteContext() );
3361 mapcanvasNode.appendChild( scopeElement );
3362
3363 // TODO: store only units, extent, projections, dest CRS
3364}
3365
3366void QgsMapCanvas::zoomByFactor( double scaleFactor, const QgsPointXY *center, bool ignoreScaleLock )
3367{
3368 if ( mScaleLocked && !ignoreScaleLock )
3369 {
3370 ScaleRestorer restorer( this );
3372 }
3373 else
3374 {
3376 r.scale( scaleFactor, center );
3377 setExtent( r, true );
3378 refresh();
3379 }
3380}
3381
3383{
3384 // Find out which layer it was that sent the signal.
3385 QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
3386 if ( layer )
3387 {
3388 emit selectionChanged( layer );
3389 refresh();
3390 }
3391}
3392
3393void QgsMapCanvas::dragEnterEvent( QDragEnterEvent *event )
3394{
3395 // By default graphics view delegates the drag events to graphics items.
3396 // But we do not want that and by ignoring the drag enter we let the
3397 // parent (e.g. QgisApp) to handle drops of map layers etc.
3398
3399 // so we ONLY accept the event if we know in advance that a custom drop handler
3400 // wants it
3401
3402 if ( QgsMimeDataUtils::isUriList( event->mimeData() ) )
3403 {
3405 bool allHandled = true;
3406 for ( const QgsMimeDataUtils::Uri &uri : lst )
3407 {
3408 bool handled = false;
3409 for ( QgsCustomDropHandler *handler : std::as_const( mDropHandlers ) )
3410 {
3411 if ( handler->canHandleCustomUriCanvasDrop( uri, this ) )
3412 {
3413 handled = true;
3414 break;
3415 }
3416 }
3417 if ( !handled )
3418 allHandled = false;
3419 }
3420 if ( allHandled )
3421 event->accept();
3422 else
3423 event->ignore();
3424 }
3425 else
3426 {
3427 event->ignore();
3428 }
3429}
3430
3432{
3433 if ( event->type() == QEvent::ToolTip && mMapTool && mMapTool->canvasToolTipEvent( qgis::down_cast<QHelpEvent *>( event ) ) )
3434 {
3435 return true;
3436 }
3437 return QGraphicsView::viewportEvent( event );
3438}
3439
3440void QgsMapCanvas::mapToolDestroyed()
3441{
3442 QgsDebugMsgLevel( u"maptool destroyed"_s, 2 );
3443 mMapTool = nullptr;
3444}
3445
3446bool QgsMapCanvas::event( QEvent *e )
3447{
3448 if ( e->type() == QEvent::Gesture )
3449 {
3450 if ( QTapAndHoldGesture *tapAndHoldGesture = qobject_cast<QTapAndHoldGesture *>( static_cast<QGestureEvent *>( e )->gesture( Qt::TapAndHoldGesture ) ) )
3451 {
3452 QPointF pos = tapAndHoldGesture->position();
3453 pos = mapFromGlobal( QPoint( pos.x(), pos.y() ) );
3454 QgsPointXY mapPoint = getCoordinateTransform()->toMapCoordinates( pos.x(), pos.y() );
3455 emit tapAndHoldGestureOccurred( mapPoint, tapAndHoldGesture );
3456 }
3457
3458 // call handler of current map tool
3459 if ( mMapTool )
3460 {
3461 return mMapTool->gestureEvent( static_cast<QGestureEvent *>( e ) );
3462 }
3463 }
3464
3465 // pass other events to base class
3466 return QGraphicsView::event( e );
3467}
3468
3470{
3471 // reload all layers in canvas
3472 const QList<QgsMapLayer *> layers = mapSettings().layers();
3473 for ( QgsMapLayer *layer : layers )
3474 {
3475 layer->reload();
3476 }
3477
3479}
3480
3482{
3483 // clear the cache
3484 clearCache();
3485
3486 // and then refresh
3487 refresh();
3488}
3489
3491{
3492 while ( mRefreshScheduled || mJob )
3493 {
3494 QgsApplication::processEvents();
3495 }
3496}
3497
3499{
3500 mSettings.setSegmentationTolerance( tolerance );
3501}
3502
3504{
3505 mSettings.setSegmentationToleranceType( type );
3506}
3507
3508QList<QgsMapCanvasAnnotationItem *> QgsMapCanvas::annotationItems() const
3509{
3510 QList<QgsMapCanvasAnnotationItem *> annotationItemList;
3511 const QList<QGraphicsItem *> items = mScene->items();
3512 for ( QGraphicsItem *gi : items )
3513 {
3514 QgsMapCanvasAnnotationItem *aItem = dynamic_cast<QgsMapCanvasAnnotationItem *>( gi );
3515 if ( aItem )
3516 {
3517 annotationItemList.push_back( aItem );
3518 }
3519 }
3520
3521 return annotationItemList;
3522}
3523
3525{
3526 mAnnotationsVisible = show;
3527 const QList<QgsMapCanvasAnnotationItem *> items = annotationItems();
3528 for ( QgsMapCanvasAnnotationItem *item : items )
3529 {
3530 item->setVisible( show );
3531 }
3532}
3533
3535{
3536 mSettings.setLabelingEngineSettings( settings );
3537}
3538
3540{
3541 return mSettings.labelingEngineSettings();
3542}
3543
3544void QgsMapCanvas::setSelectiveMaskingSourceSets( const QVector<QgsSelectiveMaskingSourceSet> &sets )
3545{
3546 mSettings.setSelectiveMaskingSourceSets( sets );
3547}
3548
3549void QgsMapCanvas::startPreviewJobs()
3550{
3551 stopPreviewJobs(); //just in case still running
3552 schedulePreviewJob( 0 );
3553}
3554
3555void QgsMapCanvas::startPreviewJob( int number )
3556{
3557 if ( number == 4 )
3558 number += 1;
3559
3560 int j = number / 3;
3561 int i = number % 3;
3562
3563 QgsMapSettings mapSettings = mSettings;
3564 mapSettings.setRotation( 0 );
3565 const QgsRectangle mapRect = mapSettings.visibleExtent();
3566 QgsPointXY jobCenter = mapRect.center();
3567 const double dx = ( i - 1 ) * mapRect.width();
3568 const double dy = ( 1 - j ) * mapRect.height();
3569 if ( !qgsDoubleNear( mSettings.rotation(), 0.0 ) )
3570 {
3571 const double radians = mSettings.rotation() * M_PI / 180;
3572 const double rdx = dx * cos( radians ) - dy * sin( radians );
3573 const double rdy = dy * cos( radians ) + dx * sin( radians );
3574 jobCenter.setX( jobCenter.x() + rdx );
3575 jobCenter.setY( jobCenter.y() + rdy );
3576 }
3577 else
3578 {
3579 jobCenter.setX( jobCenter.x() + dx );
3580 jobCenter.setY( jobCenter.y() + dy );
3581 }
3582 const QgsRectangle jobExtent = QgsRectangle::fromCenterAndSize( jobCenter, mapRect.width(), mapRect.height() );
3583
3584 //copy settings, only update extent
3585 QgsMapSettings jobSettings = mSettings;
3586 jobSettings.setExtent( jobExtent );
3587 jobSettings.setFlag( Qgis::MapSettingsFlag::DrawLabeling, false );
3589 // never profile preview jobs
3590 jobSettings.setFlag( Qgis::MapSettingsFlag::RecordProfile, false );
3591
3592 // truncate preview layers to fast layers
3593 const QList<QgsMapLayer *> layers = jobSettings.layers();
3594 QList<QgsMapLayer *> previewLayers;
3595 QgsDataProvider::PreviewContext context;
3597 for ( QgsMapLayer *layer : layers )
3598 {
3599 if ( layer->customProperty( u"rendering/noPreviewJobs"_s, false ).toBool() )
3600 {
3601 QgsDebugMsgLevel( u"Layer %1 not rendered because it is explicitly blocked from preview jobs"_s.arg( layer->id() ), 3 );
3602 continue;
3603 }
3604 context.lastRenderingTimeMs = mLastLayerRenderTime.value( layer->id(), 0 );
3605 QgsDataProvider *provider = layer->dataProvider();
3606 if ( provider && !provider->renderInPreview( context ) )
3607 {
3608 QgsDebugMsgLevel( u"Layer %1 not rendered because it does not match the renderInPreview criterion %2"_s.arg( layer->id() ).arg( mLastLayerRenderTime.value( layer->id() ) ), 3 );
3609 continue;
3610 }
3611
3612 previewLayers << layer;
3613 }
3614 if ( ( mFlags & Qgis::MapCanvasFlag::ShowMainAnnotationLayer ) && QgsProject::instance()->mainAnnotationLayer()->dataProvider()->renderInPreview( context ) )
3615 {
3616 previewLayers.insert( 0, QgsProject::instance()->mainAnnotationLayer() );
3617 }
3618 jobSettings.setLayers( filterLayersForRender( previewLayers ) );
3619
3620 QgsMapRendererQImageJob *job = new QgsMapRendererSequentialJob( jobSettings );
3621 job->setProperty( "number", number );
3622 mPreviewJobs.append( job );
3623 connect( job, &QgsMapRendererJob::finished, this, &QgsMapCanvas::previewJobFinished );
3624 job->start();
3625}
3626
3627void QgsMapCanvas::stopPreviewJobs()
3628{
3629 mPreviewTimer.stop();
3630 for ( auto previewJob = mPreviewJobs.constBegin(); previewJob != mPreviewJobs.constEnd(); ++previewJob )
3631 {
3632 if ( *previewJob )
3633 {
3634 disconnect( *previewJob, &QgsMapRendererJob::finished, this, &QgsMapCanvas::previewJobFinished );
3635 connect( *previewJob, &QgsMapRendererQImageJob::finished, *previewJob, &QgsMapRendererQImageJob::deleteLater );
3636 ( *previewJob )->cancelWithoutBlocking();
3637 }
3638 }
3639 mPreviewJobs.clear();
3640}
3641
3642void QgsMapCanvas::schedulePreviewJob( int number )
3643{
3644 mPreviewTimer.setSingleShot( true );
3645 mPreviewTimer.setInterval( Qgis::PREVIEW_JOB_DELAY_MS );
3646 disconnect( mPreviewTimerConnection );
3647 mPreviewTimerConnection = connect( &mPreviewTimer, &QTimer::timeout, this, [this, number]() { startPreviewJob( number ); } );
3648 mPreviewTimer.start();
3649}
3650
3651bool QgsMapCanvas::panOperationInProgress()
3652{
3653 if ( mCanvasProperties->panSelectorDown )
3654 return true;
3655
3656 if ( QgsMapToolPan *panTool = qobject_cast<QgsMapToolPan *>( mMapTool ) )
3657 {
3658 if ( panTool->isDragging() )
3659 return true;
3660 }
3661
3662 return false;
3663}
3664
3665int QgsMapCanvas::nextZoomLevel( const QList<double> &resolutions, bool zoomIn ) const
3666{
3667 int resolutionLevel = -1;
3668 double currentResolution = mapUnitsPerPixel();
3669 int nResolutions = resolutions.size();
3670
3671 for ( int i = 0; i < nResolutions; ++i )
3672 {
3673 if ( qgsDoubleNear( resolutions[i], currentResolution, 0.0001 ) )
3674 {
3675 resolutionLevel = zoomIn ? ( i - 1 ) : ( i + 1 );
3676 break;
3677 }
3678 else if ( currentResolution <= resolutions[i] )
3679 {
3680 resolutionLevel = zoomIn ? ( i - 1 ) : i;
3681 break;
3682 }
3683 resolutionLevel = zoomIn ? i : i + 1;
3684 }
3685
3686 if ( resolutionLevel < 0 || resolutionLevel >= nResolutions )
3687 {
3688 return -1;
3689 }
3690 if ( zoomIn && resolutionLevel == nResolutions - 1 && resolutions[nResolutions - 1] < currentResolution / mWheelZoomFactor )
3691 {
3692 // Avoid jumping straight to last resolution when zoomed far out and zooming in
3693 return -1;
3694 }
3695 if ( !zoomIn && resolutionLevel == 0 && resolutions[0] > mWheelZoomFactor * currentResolution )
3696 {
3697 // Avoid jumping straight to first resolution when zoomed far in and zooming out
3698 return -1;
3699 }
3700 return resolutionLevel;
3701}
3702
3704{
3705 if ( !mZoomResolutions.isEmpty() )
3706 {
3707 int zoomLevel = nextZoomLevel( mZoomResolutions, true );
3708 if ( zoomLevel != -1 )
3709 {
3710 return mZoomResolutions.at( zoomLevel ) / mapUnitsPerPixel();
3711 }
3712 }
3713 return 1 / mWheelZoomFactor;
3714}
3715
3717{
3718 if ( !mZoomResolutions.isEmpty() )
3719 {
3720 int zoomLevel = nextZoomLevel( mZoomResolutions, false );
3721 if ( zoomLevel != -1 )
3722 {
3723 return mZoomResolutions.at( zoomLevel ) / mapUnitsPerPixel();
3724 }
3725 }
3726 return mWheelZoomFactor;
3727}
static const int PREVIEW_JOB_DELAY_MS
Delay between the scheduling of 2 preview jobs.
Definition qgis.h:6717
QFlags< MapSettingsFlag > MapSettingsFlags
Map settings flags.
Definition qgis.h:2887
@ MediumString
A medium-length string, recommended for general purpose use.
Definition qgis.h:2553
DistanceUnit
Units of distance.
Definition qgis.h:5269
@ Degrees
Degrees, for planar geographic CRS distance measurements.
Definition qgis.h:5276
@ ShowMainAnnotationLayer
The project's main annotation layer should be rendered in the canvas.
Definition qgis.h:3625
static const int MAXIMUM_LAYER_PREVIEW_TIME_MS
Maximum rendering time for a layer of a preview job.
Definition qgis.h:6720
@ Animated
Temporal navigation relies on frames within a datetime range.
Definition qgis.h:2677
@ Movie
Movie mode – behaves like a video player, with a fixed frame duration and no temporal range.
Definition qgis.h:2679
@ FixedRange
Temporal navigation relies on a fixed datetime range.
Definition qgis.h:2678
@ Disabled
Temporal navigation is disabled.
Definition qgis.h:2676
@ Warning
Warning message.
Definition qgis.h:162
@ AffectsLabeling
If present, indicates that the renderer will participate in the map labeling problem.
Definition qgis.h:876
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
Definition qgis.h:379
@ Point
Points.
Definition qgis.h:380
@ Line
Lines.
Definition qgis.h:381
@ Polygon
Polygons.
Definition qgis.h:382
@ Group
Composite group layer. Added in QGIS 3.24.
Definition qgis.h:214
@ Plugin
Plugin based layer.
Definition qgis.h:209
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
Definition qgis.h:215
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
Definition qgis.h:212
@ Vector
Vector layer.
Definition qgis.h:207
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
Definition qgis.h:211
@ Mesh
Mesh layer. Added in QGIS 3.2.
Definition qgis.h:210
@ Raster
Raster layer.
Definition qgis.h:208
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
Definition qgis.h:213
@ YX
Northing/Easting (or Latitude/Longitude for geographic CRS).
Definition qgis.h:2539
@ View
Renderer used for displaying on screen.
Definition qgis.h:3612
QFlags< MapCanvasFlag > MapCanvasFlags
Flags controlling behavior of map canvases.
Definition qgis.h:3634
@ Preferred
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
Definition qgis.h:2579
@ BallparkTransformsAreAppropriate
Indicates that approximate "ballpark" results are appropriate for this coordinate transform....
Definition qgis.h:2829
@ IgnoreImpossibleTransformations
Indicates that impossible transformations (such as those which attempt to transform between two diffe...
Definition qgis.h:2831
@ DrawEditingInfo
Enable drawing of vertex markers for layers in editing mode.
Definition qgis.h:2865
@ RenderPreviewJob
Render is a 'canvas preview' render, and shortcuts should be taken to ensure fast rendering.
Definition qgis.h:2874
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
Definition qgis.h:2872
@ RecordProfile
Enable run-time profiling while rendering.
Definition qgis.h:2882
@ UseRenderingOptimization
Enable vector simplification and other rendering optimizations.
Definition qgis.h:2869
@ RenderPartialOutput
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
Definition qgis.h:2873
@ Antialiasing
Enable anti-aliasing for map rendering.
Definition qgis.h:2864
@ DrawLabeling
Enable drawing of labels on top of the map.
Definition qgis.h:2868
@ HighQualityImageTransforms
Enable high quality image transformations, which results in better appearance of scaled or rotated ra...
Definition qgis.h:2879
Abstract base class for all 2D map controllers.
SegmentationToleranceType
Segmentation tolerance as maximum angle or maximum difference between approximation and circle.
virtual bool isEmpty() const
Returns true if the geometry is empty.
Represents a map layer containing a set of georeferenced annotations, e.g.
static QCursor getThemeCursor(Cursor cursor)
Helper to get a theme cursor.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QgsImageCache * imageCache()
Returns the application's image cache, used for caching resampled versions of raster images.
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
static QgsSvgCache * svgCache()
Returns the application's SVG cache, used for caching SVG images and handling parameter replacement w...
static QgsCoordinateReferenceSystemRegistry * coordinateReferenceSystemRegistry()
Returns the application's coordinate reference system (CRS) registry, which handles known CRS definit...
void userCrsChanged(const QString &id)
Emitted whenever an existing user CRS definition is changed.
static Qgis::CoordinateOrder defaultCoordinateOrderForCrs(const QgsCoordinateReferenceSystem &crs)
Returns the default coordinate order to use for the specified crs.
static QString axisDirectionToAbbreviatedString(Qgis::CrsAxisDirection axis)
Returns a translated abbreviation representing an axis direction.
Represents a coordinate reference system (CRS).
void updateDefinition()
Updates the definition and parameters of the coordinate reference system to their latest values.
Handles coordinate transforms between two coordinate systems.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
Abstract base class that may be implemented to handle new types of data to be dropped in QGIS.
virtual bool renderInPreview(const QgsDataProvider::PreviewContext &context)
Returns whether the layer must be rendered in preview jobs.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
QgsRange which stores a range of double values.
Definition qgsrange.h:217
QString what() const
Abstract interface for generating an expression context scope.
Single scope for storing variables and functions for use within a QgsExpressionContext.
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes scope variables to an XML element.
bool removeVariable(const QString &name)
Removes a variable from the context scope, if found.
void setVariable(const QString &name, const QVariant &value, bool isStatic=false)
Convenience method for setting a variable in the context scope by name name and value.
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
static QgsExpressionContextScope * atlasScope(const QgsLayoutAtlas *atlas)
Creates a new scope which contains variables and functions relating to a QgsLayoutAtlas.
static QgsExpressionContextScope * mapSettingsScope(const QgsMapSettings &mapSettings)
Creates a new scope which contains variables and functions relating to a QgsMapSettings object.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setLimit(long long limit)
Set the maximum number of features to request.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
void remoteImageFetched(const QString &url)
Emitted when the cache has finished retrieving an image file from a remote url.
Stores global configuration for labeling engine.
Stores computed placement from labeling engine.
static void warning(const QString &msg)
Goes to qWarning.
An interactive map canvas item which displays a QgsAnnotation.
An interface for objects which block interactions with a QgsMapCanvas.
Interaction
Available interactions to block.
An abstract class for items that can be placed on the map canvas.
virtual void updatePosition()
called on changed extent or resize event to update position of the item
Snapping utils instance that is connected to a canvas and updates the configuration (map settings + c...
Deprecated to be deleted, stuff from here should be moved elsewhere.
QPoint mouseLastXY
Last seen point of the mouse.
bool panSelectorDown
Flag to indicate the pan selector key is held down by user.
CanvasProperties()=default
Constructor for CanvasProperties.
QPoint rubberStartPoint
Beginning point of a rubber band.
bool mouseButtonDown
Flag to indicate status of mouse button.
void setCurrentLayer(QgsMapLayer *layer)
void contextMenuAboutToShow(QMenu *menu, QgsMapMouseEvent *event)
Emitted before the map canvas context menu will be shown.
void zoomToProjectExtent()
Zoom to the full extent the project associated with this canvas.
void panToSelected(QgsMapLayer *layer=nullptr)
Pan to the selected features of current ayer keeping same extent.
void freeze(bool frozen=true)
Freezes/thaws the map canvas.
void enableAntiAliasing(bool flag)
used to determine if anti-aliasing is enabled or not
void zoomToSelected(QgsMapLayer *layer=nullptr)
Zoom to the extent of the selected features of provided map layer.
void setSnappingUtils(QgsSnappingUtils *utils)
Assign an instance of snapping utils to the map canvas.
bool isCachingEnabled() const
Check whether images of rendered layers are curerently being cached.
void zoomToFullExtent()
Zoom to the full extent of all layers currently visible in the canvas.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the list of layers that should be shown in the canvas.
void setProject(QgsProject *project)
Sets the project linked to this canvas.
const QgsRenderedItemResults * renderedItemResults(bool allowOutdatedResults=true) const
Gets access to the rendered item results (may be nullptr), which includes the results of rendering an...
void setMapController(QgsAbstract2DMapController *controller)
Sets the input controller device to use for controlling the canvas.
QColor selectionColor() const
Returns color for selected features.
bool event(QEvent *e) override
~QgsMapCanvas() override
void setCachingEnabled(bool enabled)
Set whether to cache images of rendered layers.
void mouseReleaseEvent(QMouseEvent *e) override
QgsDoubleRange zRange() const
Returns the range of z-values which will be visible in the map.
void setExtent(const QgsRectangle &r, bool magnified=false)
Sets the extent of the map canvas to the specified rectangle.
void setRenderFlag(bool flag)
Sets whether a user has disabled canvas renders via the GUI.
void selectionChanged(QgsMapLayer *layer)
Emitted when selection in any layer gets changed.
QList< QgsMapCanvasAnnotationItem * > annotationItems() const
Returns a list of all annotation items in the canvas.
void updateCanvasItemPositions()
called on resize or changed extent to notify canvas items to change their rectangle
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
void extentsChanged()
Emitted when the extents of the map change.
QgsExpressionContextScope * defaultExpressionContextScope() const
Creates a new scope which contains default variables and functions relating to the map canvas.
void xyCoordinates(const QgsPointXY &p)
Emits current mouse position.
void setFlags(Qgis::MapCanvasFlags flags)
Sets flags which control how the map canvas behaves.
void stopRendering()
stop rendering (if there is any right now)
bool previewJobsEnabled
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets global labeling engine settings in the internal map settings.
QgsPointXY center() const
Gets map center, in geographical coordinates.
void showEvent(QShowEvent *event) override
int layerCount() const
Returns number of layers on the map.
void emitExtentsChanged()
Emits the extentsChanged signal when appropriate.
bool antiAliasingEnabled() const
true if antialiasing is enabled
void setPreviewMode(QgsPreviewEffect::PreviewMode mode)
Sets a preview mode for the map canvas.
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
void layerStateChange()
This slot is connected to the visibility change of one or more layers.
QgsPreviewEffect::PreviewMode previewMode() const
Returns the current preview mode for the map canvas.
void zoomScale(double scale, bool ignoreScaleLock=false)
Zooms the canvas to a specific scale.
void zoomWithCenter(int x, int y, bool zoomIn)
Zooms in/out with a given center.
QPoint mouseLastXY()
returns last position of mouse cursor
void clearCache()
Make sure to remove any rendered images from cache (does nothing if cache is not enabled).
void tapAndHoldGestureOccurred(const QgsPointXY &mapPoint, QTapAndHoldGesture *gesture)
Emitted whenever a tap and hold gesture occurs at the specified map point.
const QgsDateTimeRange & temporalRange() const
Returns map canvas datetime range.
void setCanvasColor(const QColor &_newVal)
Write property of QColor bgColor.
void panDistanceBearingChanged(double distance, Qgis::DistanceUnit unit, double bearing)
Emitted whenever the distance or bearing of an in-progress panning operation is changed.
void zoomByFactor(double scaleFactor, const QgsPointXY *center=nullptr, bool ignoreScaleLock=false)
Zoom with the factor supplied.
const QgsTemporalController * temporalController() const
Gets access to the temporal controller that will be used to update the canvas temporal range.
void flashGeometries(const QList< QgsGeometry > &geometries, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), const QColor &startColor=QColor(255, 0, 0, 255), const QColor &endColor=QColor(255, 0, 0, 0), int flashes=3, int duration=500)
Causes a set of geometries to flash within the canvas.
void setMapUpdateInterval(int timeMilliseconds)
Set how often map preview should be updated while it is being rendered (in milliseconds).
bool setReferencedExtent(const QgsReferencedRectangle &extent)
Sets the canvas to the specified extent.
void dragEnterEvent(QDragEnterEvent *e) override
QgsMapRendererCache * cache()
Returns the map renderer cache, if caching is enabled.
bool isDrawing()
Find out whether rendering is in progress.
void zRangeChanged()
Emitted when the map canvas z (elevation) range changes.
void keyPressEvent(QKeyEvent *e) override
void setZRange(const QgsDoubleRange &range)
Sets the range of z-values which will be visible in the map.
void clearExtentHistory()
Clears the list of extents and sets current extent as first item.
void zoomToPreviousExtent()
Zoom to the previous extent (view).
void enableMapTileRendering(bool flag)
sets map tile rendering flag
void panAction(QMouseEvent *event)
Called when mouse is moving and pan is activated.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the stored overrides of styles for rendering layers.
QList< QgsMapLayer * > layers(bool expandGroupLayers=false) const
Returns the list of layers shown within the map canvas.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns global labeling engine settings from the internal map settings.
void scaleChanged(double scale)
Emitted when the scale of the map changes.
void mapToolSet(QgsMapTool *newTool, QgsMapTool *oldTool)
Emit map tool changed with the old tool.
void canvasColorChanged()
Emitted when canvas background color changes.
double zoomInFactor() const
Returns the zoom in factor.
void saveAsImage(const QString &fileName, QPixmap *QPixmap=nullptr, const QString &="PNG")
Save the contents of the map canvas to disk as an image.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
void setTemporalRange(const QgsDateTimeRange &range)
Set datetime range for the map canvas.
void moveCanvasContents(bool reset=false)
called when panning is in action, reset indicates end of panning
void magnificationChanged(double magnification)
Emitted when the scale of the map changes.
void zoomOut()
Zoom out with fixed factor.
void currentLayerChanged(QgsMapLayer *layer)
Emitted when the current layer is changed.
void setTemporalController(QgsTemporalController *controller)
Sets the temporal controller for this canvas.
void renderErrorOccurred(const QString &error, QgsMapLayer *layer)
Emitted whenever an error is encountered during a map render operation.
void addOverlayWidget(QWidget *widget, Qt::Edge edge)
Adds an overlay widget to the layout, which will be bound to the specified edge.
void waitWhileRendering()
Blocks until the rendering job has finished.
void mapRefreshCanceled()
Emitted when the pending map refresh has been canceled.
double magnificationFactor() const
Returns the magnification factor.
void writeProject(QDomDocument &)
called to write map canvas settings to project
void mousePressEvent(QMouseEvent *e) override
void updateScale()
Emits signal scaleChanged to update scale in main window.
void setMagnificationFactor(double factor, const QgsPointXY *center=nullptr)
Sets the factor of magnification to apply to the map canvas.
void refreshAllLayers()
Reload all layers (including refreshing layer properties from their data sources),...
void unsetMapTool(QgsMapTool *mapTool)
Unset the current map tool or last non zoom tool.
void panActionEnd(QPoint releasePoint)
Ends pan action and redraws the canvas.
void resizeEvent(QResizeEvent *e) override
double zoomOutFactor() const
Returns the zoom in factor.
void renderStarting()
Emitted when the canvas is about to be rendered.
void setMapSettingsFlags(Qgis::MapSettingsFlags flags)
Resets the flags for the canvas' map settings.
std::unique_ptr< CanvasProperties > mCanvasProperties
Handle pattern for implementation object.
QgsStatusBar * statusBar()
Returns the associated status bar.
void keyReleased(QKeyEvent *e)
Emit key release event.
QgsMapTool * mapTool() const
Returns the currently active tool.
void setWheelFactor(double factor)
Sets wheel zoom factor (should be greater than 1).
void setStatusBar(QgsStatusBar *bar)
Sets the associated status bar.
void setAnnotationsVisible(bool visible)
Sets whether annotations are visible in the canvas.
void layerStyleOverridesChanged()
Emitted when the configuration of overridden layer styles changes.
QgsMapCanvas(QWidget *parent=nullptr)
Constructor.
void panActionStart(QPoint releasePoint)
Starts a pan action.
void zoomNextStatusChanged(bool available)
Emitted when zoom next status changed.
void setPreviewJobsEnabled(bool enabled)
Sets whether canvas map preview jobs (low priority render jobs which render portions of the view just...
QgsRectangle fullExtent() const
Returns the combined extent for all layers on the map canvas.
void redrawAllLayers()
Clears all cached images and redraws all layers.
void keyReleaseEvent(QKeyEvent *e) override
bool isFrozen() const
Returns true if canvas is frozen.
void rotationChanged(double rotation)
Emitted when the rotation of the map changes.
void panToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids, bool alwaysRecenter=true)
Centers canvas extent to feature ids.
void messageEmitted(const QString &title, const QString &message, Qgis::MessageLevel level=Qgis::MessageLevel::Info)
emit a message (usually to be displayed in a message bar)
void scaleLockChanged(bool locked)
Emitted when the scale locked state of the map changes.
const QgsLabelingResults * labelingResults(bool allowOutdatedResults=true) const
Gets access to the labeling results (may be nullptr).
void mouseMoveEvent(QMouseEvent *e) override
QgsRectangle projectExtent() const
Returns the associated project's full extent, in the canvas' CRS.
void setCenter(const QgsPointXY &center)
Set the center of the map canvas, in geographical coordinates.
void setParallelRenderingEnabled(bool enabled)
Set whether the layers are rendered in parallel or sequentially.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Sets destination coordinate reference system.
void flashFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids, const QColor &startColor=QColor(255, 0, 0, 255), const QColor &endColor=QColor(255, 0, 0, 0), int flashes=3, int duration=500)
Causes a set of features with matching ids from a vector layer to flash within the canvas.
void installInteractionBlocker(QgsMapCanvasInteractionBlocker *blocker)
Installs an interaction blocker onto the canvas, which may prevent certain map canvas interactions fr...
bool isParallelRenderingEnabled() const
Check whether the layers are rendered in parallel or sequentially.
double scale() const
Returns the last reported scale of the canvas.
QgsSnappingUtils * snappingUtils() const
Returns snapping utility class that is associated with map canvas.
Qgis::DistanceUnit mapUnits() const
Convenience function for returning the current canvas map units.
double rotation() const
Gets the current map canvas rotation in clockwise degrees.
void temporalRangeChanged()
Emitted when the map canvas temporal range changes.
void paintEvent(QPaintEvent *e) override
void zoomLastStatusChanged(bool available)
Emitted when zoom last status changed.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
void themeChanged(const QString &theme)
Emitted when the canvas has been assigned a different map theme.
void destinationCrsChanged()
Emitted when map CRS has changed.
void transformContextChanged()
Emitted when the canvas transform context is changed.
void keyPressed(QKeyEvent *e)
Emit key press event.
void setMapTool(QgsMapTool *mapTool, bool clean=false)
Sets the map tool currently being used on the canvas.
QColor canvasColor() const
Read property of QColor bgColor.
void mapCanvasRefreshed()
Emitted when canvas finished a refresh request.
int mapUpdateInterval() const
Find out how often map preview should be updated while it is being rendered (in milliseconds).
void setSelectionColor(const QColor &color)
Set color of selected vector features.
double mapUnitsPerPixel() const
Returns the mapUnitsPerPixel (map units per pixel) for the canvas.
void mouseDoubleClickEvent(QMouseEvent *e) override
void selectionChangedSlot()
Receives signal about selection change, and pass it on with layer info.
bool viewportEvent(QEvent *event) override
void setCustomDropHandlers(const QVector< QPointer< QgsCustomDropHandler > > &handlers)
Sets a list of custom drop handlers to use when drop events occur on the canvas.
void zoomToNextExtent()
Zoom to the next extent (view).
void layersChanged()
Emitted when a new set of layers has been received.
void zoomToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids)
Set canvas extent to the bounding box of a set of features.
void setSelectiveMaskingSourceSets(const QVector< QgsSelectiveMaskingSourceSet > &sets)
Sets a list of all selective masking source sets defined for the map canvas.
void renderComplete(QPainter *painter)
Emitted when the canvas has rendered.
void zoomIn()
Zoom in with fixed factor.
QgsMapLayer * layer(int index)
Returns the map layer at position index in the layer stack.
void cancelJobs()
Cancel any rendering job, in a blocking way.
Qgis::MapCanvasFlags flags() const
Returns flags which control how the map canvas behaves.
bool allowInteraction(QgsMapCanvasInteractionBlocker::Interaction interaction) const
Returns true if the specified interaction is currently permitted on the canvas.
void wheelEvent(QWheelEvent *e) override
bool previewModeEnabled() const
Returns whether a preview mode is enabled for the map canvas.
static const QgsSettingsEntryString * settingsCustomCoordinateCrs
const QgsMapToPixel * getCoordinateTransform()
Gets the current coordinate transform.
void dropEvent(QDropEvent *event) override
void setPreviewModeEnabled(bool previewEnabled)
Enables a preview mode for the map canvas.
QgsProject * project()
Returns the project linked to this canvas.
void setScaleLocked(bool isLocked)
Lock the scale, so zooming can be performed using magnication.
void setRotation(double degrees)
Set the rotation of the map canvas in clockwise degrees.
void removeInteractionBlocker(QgsMapCanvasInteractionBlocker *blocker)
Removes an interaction blocker from the canvas.
void readProject(const QDomDocument &)
called to read map canvas settings from project
void setTheme(const QString &theme)
Sets a map theme to show in the canvas.
void zoomToFeatureExtent(QgsRectangle &rect)
Zooms to feature extent.
QMap< QString, QString > layerStyleOverrides() const
Returns the stored overrides of styles for layers.
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
QgsRectangle extent() const
Returns the current zoom extent of the map canvas.
void refresh()
Repaints the canvas map.
QgsMapLayer * currentLayer()
returns current layer (set by legend widget)
@ FlagDontInvalidateCachedRendersWhenRangeChanges
Any cached rendering will not be invalidated when z range context is modified.
static QgsRectangle combinedExtent(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &transformContext)
Returns the combined extent of a list of layers.
Base class for all map layer types.
Definition qgsmaplayer.h:83
void autoRefreshIntervalChanged(int interval)
Emitted when the auto refresh interval changes.
Qgis::LayerType type
Definition qgsmaplayer.h:93
void rendererChanged()
Signal emitted when renderer is changed.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
A mouse event which is the result of a user interaction with a QgsMapCanvas.
Responsible for keeping a cache of rendered images resulting from a map rendering job.
Job implementation that renders everything sequentially using a custom painter.
void waitForFinished() override
Block until the job has finished.
const QgsMapSettings & mapSettings() const
Returns map settings with which this job was started.
void finished()
emitted when asynchronous rendering is finished (or canceled).
static const QgsSettingsEntryBool * settingsLogCanvasRefreshEvent
Settings entry log canvas refresh event.
void start()
Start the rendering job and immediately return.
QList< QgsMapRendererJob::Error > Errors
virtual QImage renderedImage()=0
Gets a preview/resulting image.
static bool isValidExtent(const QgsRectangle &extent)
Returns true if an extent is a valid extent which can be used by QgsMapSettings.
static QString worldFileContent(const QgsMapSettings &mapSettings)
Creates the content of a world file.
Contains configuration for rendering maps.
Qgis::DistanceUnit mapUnits() const
Returns the units of the map's geographical coordinates - used for scale calculation.
QList< QgsMapLayer * > layers(bool expandGroupLayers=false) const
Returns the list of layers which will be rendered in the map.
QPolygonF visiblePolygon() const
Returns the visible area as a polygon (may be rotated).
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the list of layers to render in the map.
double scale() const
Returns the calculated map scale.
void setFrameRate(double rate)
Sets the frame rate of the map (in frames per second), for maps which are part of an animation.
QgsRectangle layerExtentToOutputExtent(const QgsMapLayer *layer, QgsRectangle extent) const
transform bounding box from layer's CRS to output CRS
const QgsMapToPixel & mapToPixel() const
double mapUnitsPerPixel() const
Returns the distance in geographical coordinates that equals to one pixel in the map.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
void setExtent(const QgsRectangle &rect, bool magnified=true)
Sets the coordinates of the rectangle which should be rendered.
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes output image size into account.
QgsRectangle fullExtent() const
returns current extent of layer set
void setCurrentFrame(long long frame)
Sets the current frame of the map, for maps which are part of an animation.
bool testFlag(Qgis::MapSettingsFlag flag) const
Check whether a particular flag is enabled.
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
QgsPointXY mapToLayerCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from output CRS to layer's CRS
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
void setFlag(Qgis::MapSettingsFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
void readXml(QDomNode &node)
Restore the map settings from a XML node.
void mapThemesChanged()
Emitted when map themes within the collection are changed.
void mapThemeRenamed(const QString &name, const QString &newName)
Emitted when a map theme within the collection is renamed.
void mapThemeChanged(const QString &theme)
Emitted when a map theme changes definition.
Perform transforms between map coordinates and device coordinates.
double mapUnitsPerPixel() const
Returns the current map units per pixel.
QgsPointXY toMapCoordinates(int x, int y) const
Transforms device coordinates to map (world) coordinates.
Abstract base class for all map tools.
Definition qgsmaptool.h:73
@ AllowZoomRect
Allow zooming by rectangle (by holding shift and dragging) while the tool is active.
Definition qgsmaptool.h:113
@ ShowContextMenu
Show a context menu when right-clicking with the tool (since QGIS 3.14). See populateContextMenu().
Definition qgsmaptool.h:114
virtual void deactivate()
called when map tool is being deactivated
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
static bool isUriList(const QMimeData *data)
QList< QgsMimeDataUtils::Uri > UriList
static UriList decodeUriList(const QMimeData *data)
A custom layout which can be used to overlay child widgets over a parent widget.
Represents a 2D point.
Definition qgspointxy.h:62
double sqrDist(double x, double y) const
Returns the squared distance between this point a specified x, y coordinate.
Definition qgspointxy.h:189
void setY(double y)
Sets the y value of the point.
Definition qgspointxy.h:132
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
void setX(double x)
Sets the x value of the point.
Definition qgspointxy.h:122
A graphics effect which can be applied to a widget to simulate various printing and color blindness m...
QgsReferencedRectangle fullExtent() const
Returns the full extent of the project, which represents the maximal limits of the project.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:113
static QgsProject * instance()
Returns the QgsProject singleton instance.
Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
void scaleMethodChanged()
Emitted when the project's scale method is changed.
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
void elevationShadingRendererChanged()
Emitted when the map shading renderer changes.
void readProject(const QDomDocument &document)
Emitted when a project is being read.
const QgsProjectViewSettings * viewSettings() const
Returns the project's view settings, which contains settings and properties relating to how a QgsProj...
void transformContextChanged()
Emitted when the project transformContext() is changed.
void writeProject(QDomDocument &document)
Emitted when the project is being written.
A container for the context for various read/write operations on objects.
A rectangle specified with double values.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
static QgsRectangle fromCenterAndSize(const QgsPointXY &center, double width, double height)
Creates a new rectangle, given the specified center point and width and height.
QgsPointXY center
void setNull()
Mark a rectangle as being null (holding no spatial information).
A QgsRectangle with associated coordinate reference system.
Stores collated details of rendered items during a map rendering operation.
Responsible for drawing transient features (e.g.
void setWidth(double width)
Sets the width of the line.
void setSecondaryStrokeColor(const QColor &color)
Sets a secondary stroke color for the rubberband which will be drawn under the main stroke color.
@ ICON_CIRCLE
A circle is used to highlight points (○).
void setStrokeColor(const QColor &color)
Sets the stroke color for the rubberband.
QColor secondaryStrokeColor
void setIcon(IconType icon)
Sets the icon type to highlight point geometries.
void updatePosition() override
called on changed extent or resize event to update position of the item
void addGeometry(const QgsGeometry &geometry, QgsMapLayer *layer, bool doUpdate=true)
Adds the geometry of an existing feature to a rubberband This is useful for multi feature highlightin...
void setFillColor(const QColor &color)
Sets the fill color for the rubberband.
void clear(const QString &group="startup")
clear Clear all profile data.
Scoped object for saving and restoring a QPainter object's state.
Scoped object for logging of the runtime for a single operation or group of operations.
A utility class for dynamic handling of changes to screen properties.
void screenDpiChanged(double dpi)
Emitted whenever the screen dpi associated with the widget is changed.
T value(const QString &dynamicKeyPart=QString()) const
Returns settings value.
bool setValue(const T &value, const QString &dynamicKeyPart=QString()) const
Set settings value.
A string settings entry.
static const QgsSettingsEntryDouble * settingsSegmentationTolerance
Settings entry segmentation tolerance for curved geometries.
static const QgsSettingsEntryBool * settingsRespectScreenDPI
Settings entry respect screen dpi.
static const QgsSettingsEntryEnumFlag< QgsAbstractGeometry::SegmentationToleranceType > * settingsSegmentationToleranceType
Settings entry segmentation tolerance type for curved geometries.
static const QgsSettingsEntryDouble * settingsZoomFactor
Settings entry zoom factor.
static const QgsSettingsEntryBool * settingsReverseWheelZoom
Settings entry reverse wheel zoom.
static QgsSettingsTreeNode * sTreeMap
Contains configuration of snapping and can return answers to snapping queries.
A proxy widget for QStatusBar.
void remoteSvgFetched(const QString &url)
Emitted when the cache has finished retrieving an SVG file from a remote url.
static double rendererFrameRate(const QgsFeatureRenderer *renderer)
Calculates the frame rate (in frames per second) at which the given renderer must be redrawn.
A controller base class for temporal objects, contains a signal for notifying updates of the objects ...
void updateTemporalRange(const QgsDateTimeRange &range)
Signals that a temporal range has changed and needs to be updated in all connected objects.
Implements a temporal controller based on a frame by frame navigation and animation.
void navigationModeChanged(Qgis::TemporalNavigationMode mode)
Emitted whenever the navigation mode changes.
@ FlagDontInvalidateCachedRendersWhenRangeChanges
Any cached rendering will not be invalidated when temporal range context is modified.
T begin() const
Returns the beginning of the range.
Definition qgsrange.h:408
T end() const
Returns the upper bound of the range.
Definition qgsrange.h:415
Temporarily sets a cursor override for the QApplication for the lifetime of the object.
void release()
Releases the cursor override early (i.e.
Represents a vector layer which manages a vector based dataset.
Q_INVOKABLE QgsRectangle boundingBoxOfSelected() const
Returns the bounding box of the selected features. If there is no selection, QgsRectangle(0,...
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
Implements a map layer that is dedicated to rendering of vector tiles.
QList< QgsFeature > selectedFeatures() const
Returns the list of features currently selected in the layer.
void selectionChanged()
Emitted whenever the selected features in the layer are changed.
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
Represent a 2-dimensional vector.
Definition qgsvector.h:34
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
constexpr double CANVAS_MAGNIFICATION_MIN
Minimum magnification level allowed in map canvases.
Definition qgsguiutils.h:62
constexpr double CANVAS_MAGNIFICATION_MAX
Maximum magnification level allowed in map canvases.
Definition qgsguiutils.h:69
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
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7077
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
Definition qgis.h:6982
QSet< QgsFeatureId > QgsFeatureIds
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
QList< QgsMapLayer * > filterLayersForRender(const QList< QgsMapLayer * > &layers)
QgsTemporalRange< QDateTime > QgsDateTimeRange
QgsRange which stores a range of date times.
Definition qgsrange.h:705
double maxRenderingTimeMs
Default maximum allowable render time, in ms.
double lastRenderingTimeMs
Previous rendering time for the layer, in ms.