81#include <QApplication>
86#include <QGraphicsItem>
87#include <QGraphicsScene>
88#include <QGraphicsView>
94#include <QPropertyAnimation>
96#include <QResizeEvent>
100#include <QTextStream>
101#include <QVariantAnimation>
102#include <QWheelEvent>
106#include "moc_qgsmapcanvas.cpp"
108using namespace Qt::StringLiterals;
145 : QGraphicsView( parent )
147 , mExpressionContextScope( tr(
"Map Canvas" ) )
149 mScene =
new QGraphicsScene();
151 setLayout( mLayout );
154 setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
155 setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
156 setMouseTracking(
true );
157 setFocusPolicy( Qt::StrongFocus );
162 mResizeTimer =
new QTimer(
this );
163 mResizeTimer->setSingleShot(
true );
166 mRefreshTimer =
new QTimer(
this );
167 mRefreshTimer->setSingleShot(
true );
168 connect( mRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::refreshMap );
171 mMap =
new QgsMapCanvasMap(
this );
210 if ( mSettings.destinationCrs() != crs )
230 QSize s = viewport()->size();
231 mSettings.setOutputSize( s );
235 setSceneRect( 0, 0, s.width(), s.height() );
236 mScene->setSceneRect( QRectF( 0, 0, s.width(), s.height() ) );
240 connect( &mMapUpdateTimer, &QTimer::timeout,
this, &QgsMapCanvas::mapUpdateTimeout );
241 mMapUpdateTimer.setInterval( 250 );
246 grabGesture( Qt::PinchGesture );
247 grabGesture( Qt::TapAndHoldGesture );
248 viewport()->setAttribute( Qt::WA_AcceptTouchEvents );
252 viewport()->setGraphicsEffect( mPreviewEffect );
256 connect( &mAutoRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::autoRefreshTriggered );
260 setInteractive(
false );
275 mMapTool->deactivate();
276 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
284 const QList<QgsMapTool *> tools = findChildren<QgsMapTool *>();
287 tool->mCanvas =
nullptr;
295 qDeleteAll( mScene->items() );
297 mScene->deleteLater();
302 mLayout->addWidget( widget, edge );
316 for (
auto previewJob = mPreviewJobs.constBegin(); previewJob != mPreviewJobs.constEnd(); ++previewJob )
324 mPreviewJobs.clear();
332 factor = std::clamp( factor, magnifierMin, magnifierMax );
335 if ( !
qgsDoubleNear( factor, mSettings.magnificationFactor(), 0.01 ) )
337 mSettings.setMagnificationFactor( factor,
center );
345 return mSettings.magnificationFactor();
367 if ( index >= 0 && index <
layers.size() )
390 if ( mCurrentLayer ==
layer )
393 mCurrentLayer =
layer;
404 return nullptr != mJob;
417 if ( !mTheme.isEmpty() )
420 setLayersPrivate(
layers );
433void QgsMapCanvas::setLayersPrivate(
const QList<QgsMapLayer *> &layers )
435 const QList<QgsMapLayer *> oldLayers = mSettings.
layers();
438 if (
layers == oldLayers )
457 QgsVectorTileLayer *vtlayer = qobject_cast<QgsVectorTileLayer *>(
layer );
473 mSettings.setLayers(
layers );
475 for ( QgsMapLayer *
layer : std::as_const(
layers ) )
482 switch (
layer->type() )
486 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>(
layer );
494 QgsVectorTileLayer *vtlayer = qobject_cast<QgsVectorTileLayer *>(
layer );
513 updateAutoRefreshTimer();
530 if ( mSettings.destinationCrs() == crs )
535 if ( !mSettings.visibleExtent().isEmpty() && crs.
isSameCelestialBody( mSettings.destinationCrs() ) )
553 mBlockExtentChangedSignal++;
554 mBlockScaleChangedSignal++;
560 mBlockItemPositionUpdates++;
562 mBlockItemPositionUpdates--;
565 mBlockExtentChangedSignal--;
566 mBlockScaleChangedSignal--;
568 mSettings.setDestinationCrs( crs );
590 mSettings.setFrameRate( -1 );
591 mSettings.setCurrentFrame( -1 );
594 mController = controller;
600void QgsMapCanvas::temporalControllerModeChanged()
604 switch ( temporalNavigationObject->navigationMode() )
608 mSettings.
setFrameRate( temporalNavigationObject->framesPerSecond() );
609 mSettings.
setCurrentFrame( temporalNavigationObject->currentFrameNumber() );
630 mSettings.setFlags(
flags );
637 if ( !allowOutdatedResults && mLabelingResultsOutdated )
640 return mLabelingResults.get();
645 if ( !allowOutdatedResults && mRenderedItemResultsOutdated )
648 return mRenderedItemResults.get();
656 if ( mJob && mJob->isActive() )
659 mJob->waitForFinished();
664 mCache = std::make_unique<QgsMapRendererCache>();
670 mPreviousRenderedItemResults.reset();
675 return nullptr != mCache.get();
683 if ( mPreviousRenderedItemResults )
684 mPreviousRenderedItemResults.reset();
685 if ( mRenderedItemResults )
686 mRenderedItemResults.reset();
696 mUseParallelRendering = enabled;
701 return mUseParallelRendering;
706 mMapUpdateTimer.setInterval( timeMilliseconds );
711 return mMapUpdateTimer.interval();
717 return mCurrentLayer;
738 expressionContext << generator->createExpressionContextScope();
741 return expressionContext;
746 if ( !mSettings.hasValidSettings() )
748 QgsDebugMsgLevel( u
"CANVAS refresh - invalid settings -> nothing to do"_s, 2 );
752 if ( !mRenderFlag || mFrozen )
758 if ( mRefreshScheduled )
764 mRefreshScheduled =
true;
769 mRefreshTimer->start( 1 );
771 mLabelingResultsOutdated =
true;
772 mRenderedItemResultsOutdated =
true;
777 QList<QgsMapLayer *> filteredLayers;
780 if (
QgsAnnotationLayer *annotationLayer = qobject_cast<QgsAnnotationLayer *>( layer ) )
782 if (
QgsMapLayer *linkedLayer = annotationLayer->linkedVisibilityLayer() )
784 if ( !layers.contains( linkedLayer ) )
788 filteredLayers.append( layer );
792 filteredLayers.erase( std::remove_if( filteredLayers.begin(), filteredLayers.end(), [](
QgsMapLayer *layer ) { return !layer || !layer->isValid(); } ), filteredLayers.end() );
794 return filteredLayers;
797void QgsMapCanvas::refreshMap()
799 Q_ASSERT( mRefreshScheduled );
806 if ( mCacheInvalidations.testFlag( CacheInvalidationType::Temporal ) )
808 clearTemporalCache();
809 mCacheInvalidations &= ~(
static_cast<int>( CacheInvalidationType::Temporal ) );
811 if ( mCacheInvalidations.testFlag( CacheInvalidationType::Elevation ) )
813 clearElevationCache();
814 mCacheInvalidations &= ~(
static_cast<int>( CacheInvalidationType::Elevation ) );
820 if ( QgsTemporalNavigationObject *temporalNavigationObject =
dynamic_cast<QgsTemporalNavigationObject *
>( mController ) )
822 switch ( temporalNavigationObject->navigationMode() )
826 mSettings.setFrameRate( temporalNavigationObject->framesPerSecond() );
827 mSettings.setCurrentFrame( temporalNavigationObject->currentFrameNumber() );
838 if ( !mTheme.isEmpty() )
846 mSettings.setLayerStyleOverrides(
QgsProject::instance()->mapThemeCollection()->mapThemeStyleOverrides( mTheme ) );
850 QgsMapSettings renderSettings = mSettings;
851 QList<QgsMapLayer *> allLayers = renderSettings.
layers();
862 mJobCanceled =
false;
863 if ( mUseParallelRendering )
864 mJob =
new QgsMapRendererParallelJob( renderSettings );
866 mJob =
new QgsMapRendererSequentialJob( renderSettings );
869 mJob->setCache( mCache.get() );
870 mJob->setLayerRenderingTimeHints( mLastLayerRenderTime );
880 mRefreshScheduled =
false;
882 mMapUpdateTimer.start();
887void QgsMapCanvas::mapThemeChanged(
const QString &theme )
889 if (
theme == mTheme )
894 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
907void QgsMapCanvas::mapThemeRenamed(
const QString &theme,
const QString &newTheme )
909 if ( mTheme.isEmpty() ||
theme != mTheme )
918void QgsMapCanvas::rendererJobFinished()
922 mMapUpdateTimer.stop();
924 notifyRendererErrors( mJob->errors() );
930 if ( !mJob->usedCachedLabels() )
932 mLabelingResults.reset( mJob->takeLabelingResults() );
934 mLabelingResultsOutdated =
false;
936 std::unique_ptr<QgsRenderedItemResults>
renderedItemResults( mJob->takeRenderedItemResults() );
938 if ( mRenderedItemResults )
940 renderedItemResults->transferResults( mRenderedItemResults.get(), mJob->layersRedrawnFromCache() );
942 if ( mPreviousRenderedItemResults )
945 renderedItemResults->transferResults( mPreviousRenderedItemResults.get(), mJob->layersRedrawnFromCache() );
948 if ( mCache && !mPreviousRenderedItemResults )
949 mPreviousRenderedItemResults = std::make_unique<QgsRenderedItemResults>( mJob->mapSettings().extent() );
951 if ( mRenderedItemResults && mPreviousRenderedItemResults )
956 mPreviousRenderedItemResults->transferResults( mRenderedItemResults.get() );
958 if ( mPreviousRenderedItemResults )
960 mPreviousRenderedItemResults->eraseResultsFromLayers( mJob->mapSettings().layerIds() );
964 mRenderedItemResultsOutdated =
false;
966 QImage img = mJob->renderedImage();
974 QString logMsg = tr(
"Canvas refresh: %1 ms" ).arg( mJob->renderingTime() );
978 if ( mDrawRenderingStats )
980 int w = img.width(), h = img.height();
981 QFont fnt = p.font();
984 int lh = p.fontMetrics().height() * 2;
985 QRect r( 0, h - lh, w, lh );
986 p.setPen( Qt::NoPen );
987 p.setBrush( QColor( 0, 0, 0, 110 ) );
989 p.setPen( Qt::white );
990 QString msg = u
"%1 :: %2 ms"_s.arg( mUseParallelRendering ? u
"PARALLEL"_s : u
"SEQUENTIAL"_s ).arg( mJob->renderingTime() );
991 p.drawText( r, msg, QTextOption( Qt::AlignCenter ) );
996 mMap->setContent( img, imageRect( img, mSettings ) );
998 mLastLayerRenderTime.clear();
999 const auto times = mJob->perLayerRenderingTime();
1000 for (
auto it = times.constBegin(); it != times.constEnd(); ++it )
1002 mLastLayerRenderTime.insert( it.key()->id(), it.value() );
1004 if ( mUsePreviewJobs && !mRefreshAfterJob )
1009 mRefreshAfterJob =
false;
1014 mJob->deleteLater();
1019 if ( mRefreshAfterJob )
1021 mRefreshAfterJob =
false;
1026void QgsMapCanvas::previewJobFinished()
1028 QgsMapRendererQImageJob *job = qobject_cast<QgsMapRendererQImageJob *>( sender() );
1034 mPreviewJobs.removeAll( job );
1036 int number = job->property(
"number" ).toInt();
1039 startPreviewJob( number + 1 );
1050 const QgsMapToPixel &m2p =
mapSettings.mapToPixel();
1054 if ( img.devicePixelRatio() !=
mapSettings.devicePixelRatio() )
1060 QgsRectangle rect( topLeft.
x(), topLeft.
y(), topLeft.
x() + img.width() * res, topLeft.
y() - img.height() * res );
1066 return mStatusBar.data();
1081 return mMessageBar.data();
1091 return mUserInputWidget.data();
1096 return mUsePreviewJobs;
1101 mUsePreviewJobs = enabled;
1106 mDropHandlers = handlers;
1109void QgsMapCanvas::clearTemporalCache()
1113 bool invalidateLabels =
false;
1117 bool alreadyInvalidatedThisLayer =
false;
1124 mCache->invalidateCacheForLayer(
layer );
1125 alreadyInvalidatedThisLayer =
true;
1131 if (
layer->temporalProperties() &&
layer->temporalProperties()->isActive() )
1133 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>(
layer ) )
1136 invalidateLabels =
true;
1142 if ( !alreadyInvalidatedThisLayer )
1144 mCache->invalidateCacheForLayer(
layer );
1147 else if ( QgsGroupLayer *gl = qobject_cast<QgsGroupLayer *>(
layer ) )
1149 const QList<QgsMapLayer *> childLayerList = gl->childLayers();
1150 for ( QgsMapLayer *childLayer : childLayerList )
1152 if ( childLayer->temporalProperties() && childLayer->temporalProperties()->isActive() )
1157 mCache->invalidateCacheForLayer(
layer );
1164 if ( invalidateLabels )
1166 mCache->clearCacheImage( u
"_labels_"_s );
1167 mCache->clearCacheImage( u
"_preview_labels_"_s );
1172void QgsMapCanvas::clearElevationCache()
1176 bool invalidateLabels =
false;
1178 for ( QgsMapLayer *
layer : layerList )
1180 if (
layer->elevationProperties() &&
layer->elevationProperties()->hasElevation() )
1182 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>(
layer ) )
1185 invalidateLabels =
true;
1191 mCache->invalidateCacheForLayer(
layer );
1193 else if ( QgsGroupLayer *gl = qobject_cast<QgsGroupLayer *>(
layer ) )
1195 const QList<QgsMapLayer *> childLayerList = gl->childLayers();
1196 for ( QgsMapLayer *childLayer : childLayerList )
1198 if ( childLayer->elevationProperties() && childLayer->elevationProperties()->hasElevation() )
1203 mCache->invalidateCacheForLayer(
layer );
1210 if ( invalidateLabels )
1212 mCache->clearCacheImage( u
"_labels_"_s );
1213 mCache->clearCacheImage( u
"_preview_labels_"_s );
1220 const QgsPointXY mapPoint =
event->originalMapPoint();
1224 QMenu *copyCoordinateMenu =
new QMenu( tr(
"Copy Coordinate" ), &menu );
1227 auto addCoordinateFormat = [&,
this](
const QString identifier,
const QgsCoordinateReferenceSystem &crs ) {
1228 const QgsCoordinateTransform ct( mSettings.destinationCrs(), crs, mSettings.transformContext() );
1231 const QgsPointXY transformedPoint = ct.transform( mapPoint );
1234 int displayPrecision = 0;
1237 QgsCoordinateTransform extentTransform = ct;
1242 displayPrecision = 0;
1244 displayPrecision = 1;
1246 displayPrecision = 2;
1248 displayPrecision = 3;
1250 displayPrecision = 4;
1252 displayPrecision = 5;
1254 displayPrecision = 6;
1256 displayPrecision = 7;
1258 displayPrecision = 8;
1260 displayPrecision = 9;
1262 catch ( QgsCsException & )
1267 const QList<Qgis::CrsAxisDirection> axisList = crs.axisOrdering();
1268 QString firstSuffix;
1269 QString secondSuffix;
1270 if ( axisList.size() >= 2 )
1276 QString firstNumber;
1277 QString secondNumber;
1280 firstNumber = QString::number( transformedPoint.
y(),
'f', displayPrecision );
1281 secondNumber = QString::number( transformedPoint.
x(),
'f', displayPrecision );
1285 firstNumber = QString::number( transformedPoint.
x(),
'f', displayPrecision );
1286 secondNumber = QString::number( transformedPoint.
y(),
'f', displayPrecision );
1289 QAction *copyCoordinateAction =
new QAction( u
"%5 (%1%2, %3%4)"_s.arg( firstNumber, firstSuffix, secondNumber, secondSuffix, identifier ), &menu );
1291 connect( copyCoordinateAction, &QAction::triggered,
this, [firstNumber, secondNumber, transformedPoint] {
1292 QClipboard *clipboard = QApplication::clipboard();
1294 const QString coordinates = firstNumber +
',' + secondNumber;
1297 if ( clipboard->supportsSelection() )
1299 clipboard->setText( coordinates, QClipboard::Selection );
1301 clipboard->setText( coordinates, QClipboard::Clipboard );
1303 copyCoordinateMenu->addAction( copyCoordinateAction );
1305 catch ( QgsCsException & )
1310 QgsCoordinateReferenceSystem wgs84( u
"EPSG:4326"_s );
1311 if ( mSettings.destinationCrs() != wgs84 && mSettings.destinationCrs().isSameCelestialBody( wgs84 ) )
1314 QgsSettings settings;
1316 if ( !customCrsString.isEmpty() )
1318 QgsCoordinateReferenceSystem customCrs( customCrsString );
1319 if ( customCrs != mSettings.destinationCrs() && customCrs != QgsCoordinateReferenceSystem( u
"EPSG:4326"_s ) )
1324 copyCoordinateMenu->addSeparator();
1325 QAction *setCustomCrsAction =
new QAction( tr(
"Set Custom CRS…" ), &menu );
1326 connect( setCustomCrsAction, &QAction::triggered,
this, [
this, customCrsString] {
1327 QgsProjectionSelectionDialog selector(
this );
1328 selector.setCrs( QgsCoordinateReferenceSystem( customCrsString ) );
1329 if ( selector.exec() )
1334 copyCoordinateMenu->addAction( setCustomCrsAction );
1336 menu.addMenu( copyCoordinateMenu );
1339 if ( !
mapTool()->populateContextMenuWithEvent( &menu,
event ) )
1340 mMapTool->populateContextMenu( &menu );
1344 if ( !menu.isEmpty() )
1345 menu.exec(
event->globalPos() );
1350 const QDateTime currentTime = QDateTime::currentDateTime();
1353 for (
const QgsMapRendererJob::Error &error : errors )
1355 const QString errorKey = error.layerID +
':' + error.message;
1356 if ( mRendererErrors.contains( errorKey ) )
1358 const QDateTime sameErrorTime = mRendererErrors.value( errorKey );
1360 if ( sameErrorTime.secsTo( currentTime ) < 60 )
1364 mRendererErrors[errorKey] = currentTime;
1371void QgsMapCanvas::updateDevicePixelFromScreen()
1373 mSettings.setDevicePixelRatio(
static_cast<float>( devicePixelRatioF() ) );
1377 if ( window()->windowHandle() )
1379 mSettings.setOutputDpi( window()->windowHandle()->screen()->physicalDotsPerInch() );
1380 mSettings.setDpiTarget( window()->windowHandle()->screen()->physicalDotsPerInch() );
1386 mSettings.setOutputDpi( window()->windowHandle()->screen()->logicalDotsPerInch() );
1387 mSettings.setDpiTarget( window()->windowHandle()->screen()->logicalDotsPerInch() );
1392void QgsMapCanvas::onElevationShadingRendererChanged()
1396 bool wasDeactivated = !mSettings.elevationShadingRenderer().isActive();
1397 mSettings.setElevationShadingRenderer( mProject->elevationShadingRenderer() );
1398 if ( mCache && wasDeactivated )
1408 mSettings.setTemporalRange( dateTimeRange );
1409 mSettings.setIsTemporal( dateTimeRange.
begin().isValid() || dateTimeRange.
end().isValid() );
1415 mCacheInvalidations |= CacheInvalidationType::Temporal;
1417 autoRefreshTriggered();
1422 return mSettings.temporalRange();
1427 mInteractionBlockers.append( blocker );
1432 mInteractionBlockers.removeAll( blocker );
1439 if ( block->blockCanvasInteraction( interaction ) )
1447 if ( mMapController )
1449 delete mMapController;
1450 mMapController =
nullptr;
1456 mMapController = controller;
1457 mMapController->setParent(
this );
1461 connect( mMapController, &QgsAbstract2DMapController::zoomMap,
this, [](
double factor ) {
zoomByFactor( factor ); } );
1465void QgsMapCanvas::mapUpdateTimeout()
1470 mMap->setContent( img, imageRect( img, mSettings ) );
1479 mJobCanceled =
true;
1482 mJob->cancelWithoutBlocking();
1500 image = theQPixmap->toImage();
1501 painter.begin( &image );
1511 image = mMap->contentImage().copy();
1512 painter.begin( &image );
1516 QStyleOptionGraphicsItem option;
1517 option.initFrom(
this );
1518 QGraphicsItem *item =
nullptr;
1519 QListIterator<QGraphicsItem *> i( items() );
1521 while ( i.hasPrevious() )
1523 item = i.previous();
1532 QPointF itemScenePos = item->scenePos();
1533 painter.translate( itemScenePos.x(), itemScenePos.y() );
1535 item->paint( &painter, &option );
1539 image.save( fileName, format.toLocal8Bit().data() );
1541 QFileInfo myInfo = QFileInfo( fileName );
1544 QString outputSuffix = myInfo.suffix();
1545 QString myWorldFileName = myInfo.absolutePath() +
'/' + myInfo.completeBaseName() +
'.' + outputSuffix.at( 0 ) + outputSuffix.at( myInfo.suffix().size() - 1 ) +
'w';
1546 QFile myWorldFile( myWorldFileName );
1547 if ( !myWorldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
1551 QTextStream myStream( &myWorldFile );
1587 if ( ( r == current ) && magnified )
1592 if ( !mSettings.hasValidSettings() )
1600 QgsDebugMsgLevel( u
"Empty extent - keeping old scale with new center!"_s, 2 );
1609 if ( mScaleLocked && magnified )
1611 ScaleRestorer restorer(
this );
1616 mSettings.setMagnificationFactor( scaleFactor, &newCenter );
1621 mSettings.setExtent( r, magnified );
1628 for (
int i = mLastExtent.size() - 1; i > mLastExtentIndex; i-- )
1630 mLastExtent.removeAt( i );
1633 if ( !mLastExtent.isEmpty() && mLastExtent.last() != mSettings.extent() )
1635 mLastExtent.append( mSettings.extent() );
1639 if ( mLastExtent.size() > 100 )
1641 mLastExtent.removeAt( 0 );
1645 mLastExtentIndex = mLastExtent.size() - 1;
1691 return mCursorPoint;
1706 mSettings.setRotation( degrees );
1713 if ( !mBlockScaleChangedSignal )
1746 if ( mLastExtentIndex > 0 )
1749 mSettings.setExtent( mLastExtent[mLastExtentIndex] );
1762 if ( mLastExtentIndex < mLastExtent.size() - 1 )
1765 mSettings.setExtent( mLastExtent[mLastExtentIndex] );
1777 mLastExtent.clear();
1778 mLastExtent.append( mSettings.extent() );
1779 mLastExtentIndex = mLastExtent.size() - 1;
1797 double closestSquaredDistance = pow( extentRect.
width(), 2.0 ) + pow( extentRect.
height(), 2.0 );
1798 bool pointFound =
false;
1802 double sqrDist = point.
sqrDist( centerLayerCoordinates );
1803 if ( sqrDist > closestSquaredDistance || sqrDist < 4 * std::numeric_limits<double>::epsilon() )
1806 closestPoint = point;
1807 closestSquaredDistance = sqrDist;
1812 rect.combineExtentWith( mSettings.layerToMapCoordinates(
layer, closestPoint ) );
1813 rect.scale( scaleFactor, &
center );
1826 layer = mCurrentLayer;
1834 switch (
layer->type() )
1856 rect = optimalExtentForPointLayer( vlayer, rect.
center() );
1868 for (
const QgsFeature &feature : selectedFeatures )
1870 if ( !feature.hasGeometry() )
1909 if ( !mapLayer || !mapLayer->isSpatial() )
1912 switch ( mapLayer->type() )
1918 if (
layer->selectedFeatureCount() == 0 )
1921 rect =
layer->boundingBoxOfSelected();
1929 rect = optimalExtentForPointLayer(
layer, rect.
center() );
1943 for (
const QgsFeature &feature : selectedFeatures )
1945 if ( !feature.hasGeometry() )
1967 if ( selectionExtent.
isNull() )
1985 QgsVectorLayer *vLayer = qobject_cast<QgsVectorLayer *>( mapLayer );
1994 layerExtent = vLayer->
extent();
1998 if ( layerExtent.
isNull() )
2004 extent.combineExtentWith( layerExtent );
2020 return mSettings.zRange();
2028 mSettings.setZRange( range );
2034 mCacheInvalidations |= CacheInvalidationType::Elevation;
2036 autoRefreshTriggered();
2072 if ( boundingBoxOfFeatureIds( ids,
layer, bbox, errorMsg ) )
2076 bbox = optimalExtentForPointLayer(
layer, bbox.
center() );
2095 if ( boundingBoxOfFeatureIds( ids,
layer, bbox, errorMsg ) )
2112 int featureCount = 0;
2120 errorMsg = tr(
"Feature does not have a geometry" );
2124 errorMsg = tr(
"Feature geometry is empty" );
2126 if ( !errorMsg.isEmpty() )
2135 if ( featureCount != ids.count() )
2137 errorMsg = tr(
"Feature not found" );
2149 layer = mCurrentLayer;
2155 switch (
layer->type() )
2173 for (
const QgsFeature &feature : selectedFeatures )
2175 if ( !feature.hasGeometry() )
2211 if ( !mapLayer || !mapLayer->isSpatial() )
2215 switch ( mapLayer->type() )
2220 if (
layer->selectedFeatureCount() == 0 )
2223 rect =
layer->boundingBoxOfSelected();
2231 rect = optimalExtentForPointLayer(
layer, rect.
center() );
2242 for (
const QgsFeature &feature : selectedFeatures )
2244 if ( !feature.hasGeometry() )
2267 if ( selectionExtent.
isNull() )
2284 QList<QgsGeometry> geoms;
2300 if ( geometries.isEmpty() )
2318 QColor startColor = color1;
2319 if ( !startColor.isValid() )
2329 startColor.setAlpha( 255 );
2331 QColor endColor = color2;
2332 if ( !endColor.isValid() )
2334 endColor = startColor;
2335 endColor.setAlpha( 0 );
2339 QVariantAnimation *animation =
new QVariantAnimation(
this );
2340 connect( animation, &QVariantAnimation::finished,
this, [animation, rb] {
2341 animation->deleteLater();
2344 connect( animation, &QPropertyAnimation::valueChanged,
this, [rb, geomType](
const QVariant &value ) {
2345 QColor
c = value.value<QColor>();
2357 animation->setDuration( duration * flashes );
2358 animation->setStartValue( endColor );
2359 double midStep = 0.2 / flashes;
2360 for (
int i = 0; i < flashes; ++i )
2362 double start =
static_cast<double>( i ) / flashes;
2363 animation->setKeyValueAt( start + midStep, startColor );
2364 double end =
static_cast<double>( i + 1 ) / flashes;
2366 animation->setKeyValueAt( end, endColor );
2368 animation->setEndValue( endColor );
2390 mMapTool->keyPressEvent( e );
2391 if ( !e->isAccepted() )
2396 double dx = std::fabs( currentExtent.
width() / 4 );
2397 double dy = std::fabs( currentExtent.
height() / 4 );
2429 if ( !e->isAutoRepeat() )
2431 mTemporaryCursorOverride = std::make_unique<QgsTemporaryCursorOverride>( Qt::ClosedHandCursor );
2437 case Qt::Key_PageUp:
2442 case Qt::Key_PageDown:
2449 mUseParallelRendering = !mUseParallelRendering;
2454 mDrawRenderingStats = !mDrawRenderingStats;
2482 mTemporaryCursorOverride.reset();
2492 mMapTool->keyReleaseEvent( e );
2497 QgsDebugMsgLevel(
"Ignoring key release: " + QString::number( e->key() ), 2 );
2510 auto me = std::make_unique<QgsMapMouseEvent>(
this, e );
2511 mMapTool->canvasDoubleClickEvent( me.get() );
2516void QgsMapCanvas::beginZoomRect( QPoint pos )
2518 mZoomRect.setRect( 0, 0, 0, 0 );
2519 mTemporaryCursorOverride = std::make_unique<QgsTemporaryCursorOverride>( mZoomCursor );
2520 mZoomDragging =
true;
2522 QColor color( Qt::blue );
2523 color.setAlpha( 63 );
2524 mZoomRubberBand->setColor( color );
2525 mZoomRect.setTopLeft( pos );
2528void QgsMapCanvas::stopZoomRect()
2530 if ( mZoomDragging )
2532 mZoomDragging =
false;
2533 mZoomRubberBand.reset(
nullptr );
2534 mTemporaryCursorOverride.reset();
2538void QgsMapCanvas::endZoomRect( QPoint pos )
2543 mZoomRect.setRight( pos.x() );
2544 mZoomRect.setBottom( pos.y() );
2547 mZoomRect = mZoomRect.normalized();
2549 if ( mZoomRect.width() < 5 && mZoomRect.height() < 5 )
2556 const QSize &zoomRectSize = mZoomRect.size();
2557 const QSize &canvasSize = mSettings.outputSize();
2558 double sfx =
static_cast<double>( zoomRectSize.width() ) / canvasSize.width();
2559 double sfy =
static_cast<double>( zoomRectSize.height() ) / canvasSize.height();
2560 double sf = std::max( sfx, sfy );
2562 QgsPointXY
c = mSettings.mapToPixel().toMapCoordinates( mZoomRect.center() );
2568void QgsMapCanvas::startPan()
2573 mTemporaryCursorOverride = std::make_unique<QgsTemporaryCursorOverride>( Qt::ClosedHandCursor );
2578void QgsMapCanvas::stopPan()
2583 mTemporaryCursorOverride.reset();
2591 if ( e->button() == Qt::MiddleButton && e->modifiers() & Qt::ShiftModifier )
2593 beginZoomRect( e->pos() );
2597 else if ( e->button() == Qt::MiddleButton )
2611 if ( mMapTool->flags() &
QgsMapTool::AllowZoomRect && e->button() == Qt::LeftButton && e->modifiers() & Qt::ShiftModifier )
2613 beginZoomRect( e->pos() );
2618 auto me = std::make_unique<QgsMapMouseEvent>(
this, e );
2619 showContextMenu( me.get() );
2624 auto me = std::make_unique<QgsMapMouseEvent>(
this, e );
2625 mMapTool->canvasPressEvent( me.get() );
2642 if ( mZoomDragging && e->button() == Qt::MiddleButton )
2644 endZoomRect( e->pos() );
2648 else if ( e->button() == Qt::MiddleButton )
2652 else if ( e->button() == Qt::BackButton )
2657 else if ( e->button() == Qt::ForwardButton )
2664 if ( mZoomDragging && e->button() == Qt::LeftButton )
2666 endZoomRect( e->pos() );
2673 auto me = std::make_unique<QgsMapMouseEvent>(
this, e );
2674 mMapTool->canvasReleaseEvent( me.get() );
2687 QGraphicsView::resizeEvent( e );
2688 mResizeTimer->start( 500 );
2690 double oldScale = mSettings.scale();
2691 QSize lastSize = viewport()->size();
2692 mSettings.setOutputSize( lastSize );
2694 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
2700 double scaleFactor = oldScale / mSettings.scale();
2704 mSettings.setExtent( r );
2718 QGraphicsView::paintEvent( e );
2723 if ( mBlockItemPositionUpdates )
2726 const QList<QGraphicsItem *> items = mScene->items();
2727 for ( QGraphicsItem *gi : items )
2744 QgsDebugMsgLevel(
"Wheel event delta " + QString::number( e->angleDelta().y() ), 2 );
2748 mMapTool->wheelEvent( e );
2749 if ( e->isAccepted() )
2753 if ( e->angleDelta().y() == 0 )
2760 bool zoomIn = reverseZoom ? e->angleDelta().y() < 0 : e->angleDelta().y() > 0;
2764 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( e->angleDelta().y() );
2766 if ( e->modifiers() & Qt::ControlModifier )
2769 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
2772 double signedWheelFactor =
zoomIn ? 1 / zoomFactor : zoomFactor;
2777 QgsPointXY newCenter( mousePos.
x() + ( ( oldCenter.
x() - mousePos.
x() ) * signedWheelFactor ), mousePos.
y() + ( ( oldCenter.
y() - mousePos.
y() ) * signedWheelFactor ) );
2785 mWheelZoomFactor = std::max( factor, 1.01 );
2814 ScaleRestorer restorer(
this );
2825 if ( mScaleLocked != isLocked )
2827 mScaleLocked = isLocked;
2840 else if ( mZoomDragging )
2842 mZoomRect.setBottomRight( e->pos() );
2843 mZoomRubberBand->setToCanvasRectangle( mZoomRect );
2844 mZoomRubberBand->show();
2851 auto me = std::make_unique<QgsMapMouseEvent>(
this, e );
2852 mMapTool->canvasMoveEvent( me.get() );
2857 if ( !panOperationInProgress() )
2869 if ( tool == mMapTool )
2871 mMapTool->reactivate();
2880 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2881 mMapTool->deactivate();
2891 connect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2892 mMapTool->activate();
2899 if ( mMapTool && mMapTool == tool )
2901 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2906 setCursor( Qt::ArrowCursor );
2927 mSettings.setBackgroundColor( color );
2930 QBrush bgBrush( color );
2931 setBackgroundBrush( bgBrush );
2934 palette.setColor( backgroundRole(), color );
2935 setPalette( palette );
2939 mScene->setBackgroundBrush( bgBrush );
2948 return mScene->backgroundBrush().color();
2953 if ( mSettings.selectionColor() == color )
2956 mSettings.setSelectionColor( color );
2960 bool hasSelectedFeatures =
false;
2961 const auto layers = mSettings.layers();
2967 hasSelectedFeatures =
true;
2972 if ( hasSelectedFeatures )
2982 return mSettings.selectionColor();
3023 return mSettings.layerStyleOverrides();
3028 if ( overrides == mSettings.layerStyleOverrides() )
3031 mSettings.setLayerStyleOverrides( overrides );
3038 if ( mTheme ==
theme )
3045 mSettings.setLayerStyleOverrides( QMap<QString, QString>() );
3052 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
3070void QgsMapCanvas::connectNotify(
const char *signal )
3077void QgsMapCanvas::layerRepaintRequested(
bool deferred )
3083void QgsMapCanvas::autoRefreshTriggered()
3089 mRefreshAfterJob =
true;
3096void QgsMapCanvas::updateAutoRefreshTimer()
3100 int minAutoRefreshInterval = -1;
3101 const auto layers = mSettings.layers();
3104 int layerRefreshInterval = 0;
3106 if (
layer->hasAutoRefreshEnabled() &&
layer->autoRefreshInterval() > 0 )
3108 layerRefreshInterval =
layer->autoRefreshInterval();
3110 else if ( QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>(
layer ) )
3112 if (
const QgsFeatureRenderer *renderer = vectorLayer->renderer() )
3115 if ( rendererRefreshRate > 0 )
3117 layerRefreshInterval = 1000 / rendererRefreshRate;
3122 if ( layerRefreshInterval == 0 )
3125 minAutoRefreshInterval = minAutoRefreshInterval > 0 ? std::min( layerRefreshInterval, minAutoRefreshInterval ) : layerRefreshInterval;
3128 if ( minAutoRefreshInterval > 0 )
3130 mAutoRefreshTimer.setInterval( minAutoRefreshInterval );
3131 mAutoRefreshTimer.start();
3135 mAutoRefreshTimer.stop();
3139void QgsMapCanvas::projectThemesChanged()
3141 if ( mTheme.isEmpty() )
3171 double dx = end.
x() - start.
x();
3172 double dy = end.
y() - start.
y();
3174 c.set(
c.x() - dx,
c.y() - dy );
3197 emit
panDistanceBearingChanged( mDa.measureLine( currentMapPoint, startMapPoint ), mDa.lengthUnits(), mDa.bearing( currentMapPoint, startMapPoint ) * 180 / M_PI );
3212 setSceneRect( -pnt.x(), -pnt.y(), viewport()->size().width(), viewport()->size().height() );
3220 bool allHandled =
true;
3223 bool handled =
false;
3226 if ( handler && handler->customUriProviderKey() == uri.providerKey )
3228 if ( handler->handleCustomUriCanvasDrop( uri,
this ) )
3252 updateDevicePixelFromScreen();
3257 if ( !mBlockExtentChangedSignal )
3268 if ( !mPreviewEffect )
3273 mPreviewEffect->setEnabled( previewEnabled );
3278 if ( !mPreviewEffect )
3283 return mPreviewEffect->isEnabled();
3288 if ( !mPreviewEffect )
3293 mPreviewEffect->setMode( mode );
3298 if ( !mPreviewEffect )
3303 return mPreviewEffect->mode();
3308 if ( !mSnappingUtils )
3314 return mSnappingUtils;
3319 mSnappingUtils = utils;
3326 QDomNodeList nodes = doc.elementsByTagName( u
"mapcanvas"_s );
3327 if ( nodes.count() )
3329 QDomNode node = nodes.item( 0 );
3332 if ( nodes.count() > 1 )
3334 for (
int i = 0; i < nodes.size(); ++i )
3336 QDomElement elementNode = nodes.at( i ).toElement();
3338 if ( elementNode.hasAttribute( u
"name"_s ) && elementNode.attribute( u
"name"_s ) == objectName() )
3340 node = nodes.at( i );
3348 if ( objectName() !=
"theMapCanvas"_L1 )
3353 if (
QgsProject::instance()->viewSettings()->restoreProjectExtentOnProjectLoad() && objectName() ==
"theMapCanvas"_L1 )
3366 QDomElement elem = node.toElement();
3367 if ( elem.hasAttribute( u
"theme"_s ) )
3369 if (
QgsProject::instance()->mapThemeCollection()->hasMapTheme( elem.attribute( u
"theme"_s ) ) )
3371 setTheme( elem.attribute( u
"theme"_s ) );
3377 const QDomNodeList scopeElements = elem.elementsByTagName( u
"expressionContextScope"_s );
3378 if ( scopeElements.size() > 0 )
3380 const QDomElement scopeElement = scopeElements.at( 0 ).toElement();
3386 QgsDebugMsgLevel( u
"Couldn't read mapcanvas information from project"_s, 2 );
3387 if ( !
project->viewSettings()->defaultViewExtent().isNull() )
3401 QDomNodeList nl = doc.elementsByTagName( u
"qgis"_s );
3404 QgsDebugError( u
"Unable to find qgis element in project file"_s );
3407 QDomNode qgisNode = nl.item( 0 );
3409 QDomElement mapcanvasNode = doc.createElement( u
"mapcanvas"_s );
3410 mapcanvasNode.setAttribute( u
"name"_s, objectName() );
3411 if ( !mTheme.isEmpty() )
3412 mapcanvasNode.setAttribute( u
"theme"_s, mTheme );
3413 mapcanvasNode.setAttribute( u
"annotationsVisible"_s, mAnnotationsVisible );
3414 qgisNode.appendChild( mapcanvasNode );
3416 mSettings.writeXml( mapcanvasNode, doc );
3419 QDomElement scopeElement = doc.createElement( u
"expressionContextScope"_s );
3427 mapcanvasNode.appendChild( scopeElement );
3434 if ( mScaleLocked && !ignoreScaleLock )
3436 ScaleRestorer restorer(
this );
3471 bool allHandled =
true;
3474 bool handled =
false;
3477 if ( handler->canHandleCustomUriCanvasDrop( uri,
this ) )
3499 if (
event->type() == QEvent::ToolTip && mMapTool && mMapTool->canvasToolTipEvent( qgis::down_cast<QHelpEvent *>(
event ) ) )
3503 return QGraphicsView::viewportEvent(
event );
3506void QgsMapCanvas::mapToolDestroyed()
3514 if ( e->type() == QEvent::Gesture )
3516 if ( QTapAndHoldGesture *tapAndHoldGesture = qobject_cast<QTapAndHoldGesture *>(
static_cast<QGestureEvent *
>( e )->gesture( Qt::TapAndHoldGesture ) ) )
3518 QPointF pos = tapAndHoldGesture->position();
3519 pos = mapFromGlobal( QPoint( pos.x(), pos.y() ) );
3527 return mMapTool->gestureEvent(
static_cast<QGestureEvent *
>( e ) );
3532 return QGraphicsView::event( e );
3558 while ( mRefreshScheduled || mJob )
3560 QgsApplication::processEvents();
3566 mSettings.setSegmentationTolerance( tolerance );
3571 mSettings.setSegmentationToleranceType( type );
3576 QList<QgsMapCanvasAnnotationItem *> annotationItemList;
3577 const QList<QGraphicsItem *> items = mScene->items();
3578 for ( QGraphicsItem *gi : items )
3583 annotationItemList.push_back( aItem );
3587 return annotationItemList;
3592 mAnnotationsVisible = show;
3596 item->setVisible( show );
3602 mSettings.setLabelingEngineSettings( settings );
3607 return mSettings.labelingEngineSettings();
3612 mSettings.setSelectiveMaskingSourceSets( sets );
3615void QgsMapCanvas::startPreviewJobs()
3618 schedulePreviewJob( 0 );
3621void QgsMapCanvas::startPreviewJob(
int number )
3631 const QgsRectangle mapRect =
mapSettings.visibleExtent();
3632 QgsPointXY jobCenter = mapRect.
center();
3633 const double dx = ( i - 1 ) * mapRect.
width();
3634 const double dy = ( 1 - j ) * mapRect.
height();
3637 const double radians = mSettings.rotation() * M_PI / 180;
3638 const double rdx = dx * cos( radians ) - dy * sin( radians );
3639 const double rdy = dy * cos( radians ) + dx * sin( radians );
3640 jobCenter.
setX( jobCenter.
x() + rdx );
3641 jobCenter.
setY( jobCenter.
y() + rdy );
3645 jobCenter.
setX( jobCenter.
x() + dx );
3646 jobCenter.
setY( jobCenter.
y() + dy );
3651 QgsMapSettings jobSettings = mSettings;
3659 const QList<QgsMapLayer *>
layers = jobSettings.
layers();
3660 QList<QgsMapLayer *> previewLayers;
3661 QgsDataProvider::PreviewContext context;
3665 if (
layer->customProperty( u
"rendering/noPreviewJobs"_s,
false ).toBool() )
3667 QgsDebugMsgLevel( u
"Layer %1 not rendered because it is explicitly blocked from preview jobs"_s.arg(
layer->id() ), 3 );
3671 QgsDataProvider *provider =
layer->dataProvider();
3674 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 );
3678 previewLayers <<
layer;
3686 QgsMapRendererQImageJob *job =
new QgsMapRendererSequentialJob( jobSettings );
3687 job->setProperty(
"number", number );
3688 mPreviewJobs.append( job );
3693void QgsMapCanvas::stopPreviewJobs()
3695 mPreviewTimer.stop();
3696 for (
auto previewJob = mPreviewJobs.constBegin(); previewJob != mPreviewJobs.constEnd(); ++previewJob )
3702 ( *previewJob )->cancelWithoutBlocking();
3705 mPreviewJobs.clear();
3708void QgsMapCanvas::schedulePreviewJob(
int number )
3710 mPreviewTimer.setSingleShot(
true );
3712 disconnect( mPreviewTimerConnection );
3713 mPreviewTimerConnection = connect( &mPreviewTimer, &QTimer::timeout,
this, [
this, number]() { startPreviewJob( number ); } );
3714 mPreviewTimer.start();
3717bool QgsMapCanvas::panOperationInProgress()
3722 if ( QgsMapToolPan *panTool = qobject_cast<QgsMapToolPan *>( mMapTool ) )
3724 if ( panTool->isDragging() )
3731int QgsMapCanvas::nextZoomLevel(
const QList<double> &resolutions,
bool zoomIn )
const
3733 int resolutionLevel = -1;
3735 int nResolutions = resolutions.size();
3737 for (
int i = 0; i < nResolutions; ++i )
3739 if (
qgsDoubleNear( resolutions[i], currentResolution, 0.0001 ) )
3741 resolutionLevel =
zoomIn ? ( i - 1 ) : ( i + 1 );
3744 else if ( currentResolution <= resolutions[i] )
3746 resolutionLevel =
zoomIn ? ( i - 1 ) : i;
3749 resolutionLevel =
zoomIn ? i : i + 1;
3752 if ( resolutionLevel < 0 || resolutionLevel >= nResolutions )
3756 if (
zoomIn && resolutionLevel == nResolutions - 1 && resolutions[nResolutions - 1] < currentResolution / mWheelZoomFactor )
3761 if ( !
zoomIn && resolutionLevel == 0 && resolutions[0] > mWheelZoomFactor * currentResolution )
3766 return resolutionLevel;
3771 if ( !mZoomResolutions.isEmpty() )
3773 int zoomLevel = nextZoomLevel( mZoomResolutions,
true );
3774 if ( zoomLevel != -1 )
3779 return 1 / mWheelZoomFactor;
3784 if ( !mZoomResolutions.isEmpty() )
3786 int zoomLevel = nextZoomLevel( mZoomResolutions,
false );
3787 if ( zoomLevel != -1 )
3792 return mWheelZoomFactor;
static const int PREVIEW_JOB_DELAY_MS
Delay between the scheduling of 2 preview jobs.
QFlags< MapSettingsFlag > MapSettingsFlags
Map settings flags.
@ MediumString
A medium-length string, recommended for general purpose use.
DistanceUnit
Units of distance.
@ Degrees
Degrees, for planar geographic CRS distance measurements.
@ ShowMainAnnotationLayer
The project's main annotation layer should be rendered in the canvas.
static const int MAXIMUM_LAYER_PREVIEW_TIME_MS
Maximum rendering time for a layer of a preview job.
@ Animated
Temporal navigation relies on frames within a datetime range.
@ Movie
Movie mode – behaves like a video player, with a fixed frame duration and no temporal range.
@ FixedRange
Temporal navigation relies on a fixed datetime range.
@ Disabled
Temporal navigation is disabled.
@ Warning
Warning message.
@ AffectsLabeling
If present, indicates that the renderer will participate in the map labeling problem.
@ Circle
A circle is used to highlight points (â—‹).
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
@ Group
Composite group layer. Added in QGIS 3.24.
@ Plugin
Plugin based layer.
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
@ Mesh
Mesh layer. Added in QGIS 3.2.
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
@ YX
Northing/Easting (or Latitude/Longitude for geographic CRS).
@ View
Renderer used for displaying on screen.
QFlags< MapCanvasFlag > MapCanvasFlags
Flags controlling behavior of map canvases.
@ Preferred
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
@ BallparkTransformsAreAppropriate
Indicates that approximate "ballpark" results are appropriate for this coordinate transform....
@ IgnoreImpossibleTransformations
Indicates that impossible transformations (such as those which attempt to transform between two diffe...
@ DrawEditingInfo
Enable drawing of vertex markers for layers in editing mode.
@ DrawLabelSelection
Whether vector selections should be change the rendering of associated labels.
@ RenderPreviewJob
Render is a 'canvas preview' render, and shortcuts should be taken to ensure fast rendering.
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
@ RecordProfile
Enable run-time profiling while rendering.
@ UseRenderingOptimization
Enable vector simplification and other rendering optimizations.
@ RenderPartialOutput
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
@ Antialiasing
Enable anti-aliasing for map rendering.
@ DrawLabeling
Enable drawing of labels on top of the map.
@ HighQualityImageTransforms
Enable high quality image transformations, which results in better appearance of scaled or rotated ra...
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).
bool isSameCelestialBody(const QgsCoordinateReferenceSystem &other) const
Returns true if other crs is associated with the same celestial body.
void updateDefinition()
Updates the definition and parameters of the coordinate reference system to their latest values.
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.
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...
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
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.
QgsUserInputWidget * userInputWidget()
Returns the user input widget associated with the map canvas.
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)
static const QgsSettingsEntryBool * settingsMainCanvasPreviewJobs
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.
static const QgsSettingsEntryBool * settingsEnableRenderCaching
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 setUserInputWidget(QgsUserInputWidget *userInputWidget)
Sets a userInputWidget, a floating widget that can be used to display additional widgets for user inp...
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...
QgsMessageBar * messageBar()
Returns the message bar associated with the map canvas.
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 ¢er)
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 zoomToLayers(const QList< QgsMapLayer * > &layers)
Zoom to the combined extent of a set of layers.
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 setMessageBar(QgsMessageBar *bar)
Sets a message bar to use alongside 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.
void autoRefreshIntervalChanged(int interval)
Emitted when the auto refresh interval changes.
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.
A bar for displaying non-blocking messages to the user.
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)
double sqrDist(double x, double y) const
Returns the squared distance between this point a specified x, y coordinate.
void setY(double y)
Sets the y value of the point.
void setX(double x)
Sets the x value of the point.
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,...
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 ¢er, double width, double height)
Creates a new rectangle, given the specified center point and width and height.
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 setIcon(Qgis::RubberBandIconType icon)
Sets the icon type to highlight point geometries.
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.
void setStrokeColor(const QColor &color)
Sets the stroke color for the rubberband.
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 boolean 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 * sTreeRendering
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.
T end() const
Returns the upper bound of the range.
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.
QgsRectangle extent() const final
Returns the extent of the layer.
virtual void updateExtents(bool force=false)
Update the extents for the 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.
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.
constexpr double CANVAS_MAGNIFICATION_MAX
Maximum magnification level allowed in map canvases.
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).
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
QSet< QgsFeatureId > QgsFeatureIds
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
QList< QgsMapLayer * > filterLayersForRender(const QList< QgsMapLayer * > &layers)
QgsTemporalRange< QDateTime > QgsDateTimeRange
QgsRange which stores a range of date times.
double maxRenderingTimeMs
Default maximum allowable render time, in ms.
double lastRenderingTimeMs
Previous rendering time for the layer, in ms.