21#include <QApplication>
25#include <QGraphicsItem>
26#include <QGraphicsScene>
27#include <QGraphicsView>
34#include <QResizeEvent>
42#include <QVariantAnimation>
43#include <QPropertyAnimation>
129 : QGraphicsView( parent )
131 , mExpressionContextScope( tr(
"Map Canvas" ) )
133 mScene =
new QGraphicsScene();
135 setLayout( mLayout );
138 setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
139 setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
140 setMouseTracking(
true );
141 setFocusPolicy( Qt::StrongFocus );
146 mResizeTimer =
new QTimer(
this );
147 mResizeTimer->setSingleShot(
true );
150 mRefreshTimer =
new QTimer(
this );
151 mRefreshTimer->setSingleShot(
true );
152 connect( mRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::refreshMap );
155 mMap =
new QgsMapCanvasMap(
this );
196 setDestinationCrs( crs );
209 double segmentationTolerance = settings.
value( QStringLiteral(
"qgis/segmentationTolerance" ),
"0.01745" ).toDouble();
214 mWheelZoomFactor = settings.
value( QStringLiteral(
"qgis/zoom_factor" ), 2 ).toDouble();
216 QSize s = viewport()->size();
221 setSceneRect( 0, 0, s.width(), s.height() );
222 mScene->setSceneRect( QRectF( 0, 0, s.width(), s.height() ) );
226 connect( &mMapUpdateTimer, &QTimer::timeout,
this, &QgsMapCanvas::mapUpdateTimeout );
227 mMapUpdateTimer.setInterval( 250 );
232 grabGesture( Qt::PinchGesture );
233 grabGesture( Qt::TapAndHoldGesture );
234 viewport()->setAttribute( Qt::WA_AcceptTouchEvents );
238 viewport()->setGraphicsEffect( mPreviewEffect );
242 connect( &mAutoRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::autoRefreshTriggered );
246 setInteractive(
false );
262 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
270 const QList< QgsMapTool * > tools = findChildren< QgsMapTool *>();
273 tool->mCanvas =
nullptr;
281 qDeleteAll( mScene->items() );
283 mScene->deleteLater();
304 for (
auto previewJob = mPreviewJobs.constBegin(); previewJob != mPreviewJobs.constEnd(); ++previewJob )
312 mPreviewJobs.clear();
320 factor = std::clamp( factor, magnifierMin, magnifierMax );
355 if ( index >= 0 && index <
layers.size() )
378 if ( mCurrentLayer ==
layer )
381 mCurrentLayer =
layer;
392 return nullptr != mJob;
405 if ( !mTheme.isEmpty() )
408 setLayersPrivate(
layers );
421void QgsMapCanvas::setLayersPrivate(
const QList<QgsMapLayer *> &layers )
423 const QList<QgsMapLayer *> oldLayers = mSettings.
layers();
426 if (
layers == oldLayers )
501 updateAutoRefreshTimer();
542 mBlockExtentChangedSignal++;
543 mBlockScaleChangedSignal++;
549 mBlockItemPositionUpdates++;
551 mBlockItemPositionUpdates--;
554 mBlockExtentChangedSignal--;
555 mBlockScaleChangedSignal--;
563 QgsDebugMsgLevel( QStringLiteral(
"refreshing after destination CRS changed" ), 2 );
583 mController = controller;
589void QgsMapCanvas::temporalControllerModeChanged()
593 switch ( temporalNavigationObject->navigationMode() )
597 mSettings.
setFrameRate( temporalNavigationObject->framesPerSecond() );
598 mSettings.
setCurrentFrame( temporalNavigationObject->currentFrameNumber() );
626 if ( !allowOutdatedResults && mLabelingResultsOutdated )
629 return mLabelingResults.get();
634 if ( !allowOutdatedResults && mRenderedItemResultsOutdated )
637 return mRenderedItemResults.get();
660 mPreviousRenderedItemResults.reset();
665 return nullptr != mCache;
673 if ( mPreviousRenderedItemResults )
674 mPreviousRenderedItemResults.reset();
675 if ( mRenderedItemResults )
676 mRenderedItemResults.reset();
686 mUseParallelRendering = enabled;
691 return mUseParallelRendering;
696 mMapUpdateTimer.setInterval( timeMilliseconds );
701 return mMapUpdateTimer.interval();
707 return mCurrentLayer;
727 expressionContext << generator->createExpressionContextScope();
731 return expressionContext;
738 QgsDebugMsgLevel( QStringLiteral(
"CANVAS refresh - invalid settings -> nothing to do" ), 2 );
742 if ( !mRenderFlag || mFrozen )
748 if ( mRefreshScheduled )
750 QgsDebugMsgLevel( QStringLiteral(
"CANVAS refresh already scheduled" ), 2 );
754 mRefreshScheduled =
true;
759 mRefreshTimer->start( 1 );
761 mLabelingResultsOutdated =
true;
762 mRenderedItemResultsOutdated =
true;
767 QList<QgsMapLayer *> filteredLayers;
770 if (
QgsAnnotationLayer *annotationLayer = qobject_cast< QgsAnnotationLayer * >( layer ) )
772 if (
QgsMapLayer *linkedLayer = annotationLayer->linkedVisibilityLayer() )
774 if ( !layers.contains( linkedLayer ) )
778 filteredLayers.append( layer );
780 return filteredLayers;
783void QgsMapCanvas::refreshMap()
785 Q_ASSERT( mRefreshScheduled );
792 if ( mCacheInvalidations.testFlag( CacheInvalidationType::Temporal ) )
794 clearTemporalCache();
795 mCacheInvalidations &= ~(
static_cast< int >( CacheInvalidationType::Temporal ) );
797 if ( mCacheInvalidations.testFlag( CacheInvalidationType::Elevation ) )
799 clearElevationCache();
800 mCacheInvalidations &= ~(
static_cast< int >( CacheInvalidationType::Elevation ) );
808 switch ( temporalNavigationObject->navigationMode() )
812 mSettings.
setFrameRate( temporalNavigationObject->framesPerSecond() );
813 mSettings.
setCurrentFrame( temporalNavigationObject->currentFrameNumber() );
824 if ( !mTheme.isEmpty() )
837 QList<QgsMapLayer *> allLayers = renderSettings.
layers();
848 mJobCanceled =
false;
849 if ( mUseParallelRendering )
866 mRefreshScheduled =
false;
868 mMapUpdateTimer.start();
873void QgsMapCanvas::mapThemeChanged(
const QString &theme )
875 if (
theme == mTheme )
880 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
893void QgsMapCanvas::mapThemeRenamed(
const QString &theme,
const QString &newTheme )
895 if ( mTheme.isEmpty() ||
theme != mTheme )
904void QgsMapCanvas::rendererJobFinished()
906 QgsDebugMsgLevel( QStringLiteral(
"CANVAS finish! %1" ).arg( !mJobCanceled ), 2 );
908 mMapUpdateTimer.stop();
910 notifyRendererErrors( mJob->
errors() );
920 mLabelingResultsOutdated =
false;
924 if ( mRenderedItemResults )
928 if ( mPreviousRenderedItemResults )
934 if ( mCache && !mPreviousRenderedItemResults )
935 mPreviousRenderedItemResults = std::make_unique< QgsRenderedItemResults >( mJob->
mapSettings().
extent() );
937 if ( mRenderedItemResults && mPreviousRenderedItemResults )
942 mPreviousRenderedItemResults->transferResults( mRenderedItemResults.get() );
944 if ( mPreviousRenderedItemResults )
950 mRenderedItemResultsOutdated =
false;
960 QString logMsg = tr(
"Canvas refresh: %1 ms" ).arg( mJob->
renderingTime() );
964 if ( mDrawRenderingStats )
966 int w = img.width(), h = img.height();
967 QFont fnt = p.font();
970 int lh = p.fontMetrics().height() * 2;
971 QRect r( 0, h - lh, w, lh );
972 p.setPen( Qt::NoPen );
973 p.setBrush( QColor( 0, 0, 0, 110 ) );
975 p.setPen( Qt::white );
976 QString msg = QStringLiteral(
"%1 :: %2 ms" ).arg( mUseParallelRendering ? QStringLiteral(
"PARALLEL" ) : QStringLiteral(
"SEQUENTIAL" ) ).arg( mJob->renderingTime() );
977 p.drawText( r, msg, QTextOption( Qt::AlignCenter ) );
982 mMap->setContent( img, imageRect( img, mSettings ) );
984 mLastLayerRenderTime.clear();
986 for (
auto it = times.constBegin(); it != times.constEnd(); ++it )
988 mLastLayerRenderTime.insert( it.key()->id(), it.value() );
990 if ( mUsePreviewJobs && !mRefreshAfterJob )
995 mRefreshAfterJob =
false;
1000 mJob->deleteLater();
1005 if ( mRefreshAfterJob )
1007 mRefreshAfterJob =
false;
1012void QgsMapCanvas::previewJobFinished()
1020 mPreviewJobs.removeAll( job );
1022 int number = job->property(
"number" ).toInt();
1025 startPreviewJob( number + 1 );
1042 QgsLogger::warning( QStringLiteral(
"The renderer map has a wrong device pixel ratio" ) );
1046 QgsRectangle rect( topLeft.
x(), topLeft.
y(), topLeft.
x() + img.width()*res, topLeft.
y() - img.height()*res );
1052 return mUsePreviewJobs;
1057 mUsePreviewJobs = enabled;
1062 mDropHandlers = handlers;
1065void QgsMapCanvas::clearTemporalCache()
1069 bool invalidateLabels =
false;
1073 bool alreadyInvalidatedThisLayer =
false;
1081 alreadyInvalidatedThisLayer =
true;
1092 invalidateLabels =
true;
1098 if ( !alreadyInvalidatedThisLayer )
1105 const QList<QgsMapLayer *> childLayerList = gl->childLayers();
1108 if ( childLayer->temporalProperties() && childLayer->temporalProperties()->isActive() )
1120 if ( invalidateLabels )
1128void QgsMapCanvas::clearElevationCache()
1132 bool invalidateLabels =
false;
1141 invalidateLabels =
true;
1151 const QList<QgsMapLayer *> childLayerList = gl->childLayers();
1154 if ( childLayer->elevationProperties() && childLayer->elevationProperties()->hasElevation() )
1166 if ( invalidateLabels )
1176 const QgsPointXY mapPoint =
event->originalMapPoint();
1180 QMenu *copyCoordinateMenu =
new QMenu( tr(
"Copy Coordinate" ), &menu );
1188 const QgsPointXY transformedPoint = ct.transform( mapPoint );
1191 int displayPrecision = 0;
1199 displayPrecision = 0;
1201 displayPrecision = 1;
1203 displayPrecision = 2;
1205 displayPrecision = 3;
1207 displayPrecision = 4;
1209 displayPrecision = 5;
1211 displayPrecision = 6;
1213 displayPrecision = 7;
1215 displayPrecision = 8;
1217 displayPrecision = 9;
1225 QString firstSuffix;
1226 QString secondSuffix;
1227 if ( axisList.size() >= 2 )
1233 QString firstNumber;
1234 QString secondNumber;
1237 firstNumber = QString::number( transformedPoint.
y(),
'f', displayPrecision );
1238 secondNumber = QString::number( transformedPoint.
x(),
'f', displayPrecision );
1242 firstNumber = QString::number( transformedPoint.
x(),
'f', displayPrecision );
1243 secondNumber = QString::number( transformedPoint.
y(),
'f', displayPrecision );
1246 QAction *copyCoordinateAction =
new QAction( QStringLiteral(
"%5 (%1%2, %3%4)" ).arg(
1247 firstNumber, firstSuffix, secondNumber, secondSuffix, identifier ), &menu );
1249 connect( copyCoordinateAction, &QAction::triggered,
this, [firstNumber, secondNumber, transformedPoint]
1251 QClipboard *clipboard = QApplication::clipboard();
1253 const QString coordinates = firstNumber +
',' + secondNumber;
1256 if ( clipboard->supportsSelection() )
1258 clipboard->setText( coordinates, QClipboard::Selection );
1260 clipboard->setText( coordinates, QClipboard::Clipboard );
1263 copyCoordinateMenu->addAction( copyCoordinateAction );
1277 const QString customCrsString = settings.
value( QStringLiteral(
"qgis/custom_coordinate_crs" ) ).toString();
1278 if ( !customCrsString.isEmpty() )
1286 copyCoordinateMenu->addSeparator();
1287 QAction *setCustomCrsAction =
new QAction( tr(
"Set Custom CRS…" ), &menu );
1288 connect( setCustomCrsAction, &QAction::triggered,
this, [ = ]
1292 if ( selector.exec() )
1297 copyCoordinateMenu->addAction( setCustomCrsAction );
1299 menu.addMenu( copyCoordinateMenu );
1307 if ( !menu.isEmpty() )
1308 menu.exec(
event->globalPos() );
1313 const QDateTime currentTime = QDateTime::currentDateTime();
1318 const QString errorKey = error.layerID +
':' + error.message;
1319 if ( mRendererErrors.contains( errorKey ) )
1321 const QDateTime sameErrorTime = mRendererErrors.value( errorKey );
1323 if ( sameErrorTime.secsTo( currentTime ) < 60 )
1327 mRendererErrors[errorKey] = currentTime;
1334void QgsMapCanvas::updateDevicePixelFromScreen()
1340 if ( window()->windowHandle() )
1342 mSettings.
setOutputDpi( window()->windowHandle()->screen()->physicalDotsPerInch() );
1343 mSettings.
setDpiTarget( window()->windowHandle()->screen()->physicalDotsPerInch() );
1349 mSettings.
setOutputDpi( window()->windowHandle()->screen()->logicalDotsPerInch() );
1350 mSettings.
setDpiTarget( window()->windowHandle()->screen()->logicalDotsPerInch() );
1355void QgsMapCanvas::onElevationShadingRendererChanged()
1361 if ( mCache && wasDeactivated )
1378 mCacheInvalidations |= CacheInvalidationType::Temporal;
1380 autoRefreshTriggered();
1390 mInteractionBlockers.append( blocker );
1395 mInteractionBlockers.removeAll( blocker );
1402 if ( block->blockCanvasInteraction( interaction ) )
1410 if ( mMapController )
1412 delete mMapController;
1413 mMapController =
nullptr;
1419 mMapController = controller;
1420 mMapController->setParent(
this );
1424 connect( mMapController, &QgsAbstract2DMapController::zoomMap,
this, [ = ](
double factor ) {
zoomByFactor( factor ); } );
1428void QgsMapCanvas::mapUpdateTimeout()
1433 mMap->setContent( img, imageRect( img, mSettings ) );
1442 mJobCanceled =
true;
1463 image = theQPixmap->toImage();
1464 painter.begin( &image );
1474 image = mMap->contentImage().copy();
1475 painter.begin( &image );
1479 QStyleOptionGraphicsItem option;
1480 option.initFrom(
this );
1481 QGraphicsItem *item =
nullptr;
1482 QListIterator<QGraphicsItem *> i( items() );
1484 while ( i.hasPrevious() )
1486 item = i.previous();
1495 QPointF itemScenePos = item->scenePos();
1496 painter.translate( itemScenePos.x(), itemScenePos.y() );
1498 item->paint( &painter, &option );
1502 image.save( fileName, format.toLocal8Bit().data() );
1504 QFileInfo myInfo = QFileInfo( fileName );
1507 QString outputSuffix = myInfo.suffix();
1508 QString myWorldFileName = myInfo.absolutePath() +
'/' + myInfo.completeBaseName() +
'.'
1509 + outputSuffix.at( 0 ) + outputSuffix.at( myInfo.suffix().size() - 1 ) +
'w';
1510 QFile myWorldFile( myWorldFileName );
1511 if ( !myWorldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
1515 QTextStream myStream( &myWorldFile );
1537 rect = ct.transformBoundingBox(
extent );
1551 if ( ( r == current ) && magnified )
1564 QgsDebugMsgLevel( QStringLiteral(
"Empty extent - keeping old scale with new center!" ), 2 );
1573 if ( mScaleLocked && magnified )
1575 ScaleRestorer restorer(
this );
1592 for (
int i = mLastExtent.size() - 1; i > mLastExtentIndex; i-- )
1594 mLastExtent.removeAt( i );
1597 if ( !mLastExtent.isEmpty() && mLastExtent.last() != mSettings.
extent() )
1599 mLastExtent.append( mSettings.
extent() );
1603 if ( mLastExtent.size() > 100 )
1605 mLastExtent.removeAt( 0 );
1609 mLastExtentIndex = mLastExtent.size() - 1;
1658 return mCursorPoint;
1680 if ( !mBlockScaleChangedSignal )
1713 if ( mLastExtentIndex > 0 )
1716 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
1729 if ( mLastExtentIndex < mLastExtent.size() - 1 )
1732 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
1744 mLastExtent.clear();
1745 mLastExtent.append( mSettings.
extent() ) ;
1746 mLastExtentIndex = mLastExtent.size() - 1;
1764 double closestSquaredDistance = pow( extentRect.
width(), 2.0 ) + pow( extentRect.
height(), 2.0 );
1765 bool pointFound =
false;
1769 double sqrDist = point.
sqrDist( centerLayerCoordinates );
1770 if ( sqrDist > closestSquaredDistance || sqrDist < 4 * std::numeric_limits<double>::epsilon() )
1773 closestPoint = point;
1774 closestSquaredDistance = sqrDist;
1780 rect.scale( scaleFactor, &
center );
1793 layer = mCurrentLayer;
1823 rect = optimalExtentForPointLayer( vlayer, rect.
center() );
1835 for (
const QgsFeature &feature : selectedFeatures )
1837 if ( !feature.hasGeometry() )
1876 if ( !mapLayer || !mapLayer->isSpatial() )
1879 switch ( mapLayer->type() )
1885 if (
layer->selectedFeatureCount() == 0 )
1888 rect =
layer->boundingBoxOfSelected();
1896 rect = optimalExtentForPointLayer(
layer, rect.
center() );
1910 for (
const QgsFeature &feature : selectedFeatures )
1912 if ( !feature.hasGeometry() )
1934 if ( selectionExtent.
isNull() )
1945 return mSettings.
zRange();
1959 mCacheInvalidations |= CacheInvalidationType::Elevation;
1961 autoRefreshTriggered();
1997 if ( boundingBoxOfFeatureIds( ids,
layer, bbox, errorMsg ) )
2001 bbox = optimalExtentForPointLayer(
layer, bbox.
center() );
2021 if ( boundingBoxOfFeatureIds( ids,
layer, bbox, errorMsg ) )
2038 int featureCount = 0;
2046 errorMsg = tr(
"Feature does not have a geometry" );
2050 errorMsg = tr(
"Feature geometry is empty" );
2052 if ( !errorMsg.isEmpty() )
2061 if ( featureCount != ids.count() )
2063 errorMsg = tr(
"Feature not found" );
2075 layer = mCurrentLayer;
2099 for (
const QgsFeature &feature : selectedFeatures )
2101 if ( !feature.hasGeometry() )
2137 if ( !mapLayer || !mapLayer->isSpatial() )
2141 switch ( mapLayer->type() )
2146 if (
layer->selectedFeatureCount() == 0 )
2149 rect =
layer->boundingBoxOfSelected();
2157 rect = optimalExtentForPointLayer(
layer, rect.
center() );
2168 for (
const QgsFeature &feature : selectedFeatures )
2170 if ( !feature.hasGeometry() )
2193 if ( selectionExtent.
isNull() )
2204 const QColor &color1,
const QColor &color2,
2205 int flashes,
int duration )
2212 QList< QgsGeometry > geoms;
2228 if ( geometries.isEmpty() )
2246 QColor startColor = color1;
2247 if ( !startColor.isValid() )
2257 startColor.setAlpha( 255 );
2259 QColor endColor = color2;
2260 if ( !endColor.isValid() )
2262 endColor = startColor;
2263 endColor.setAlpha( 0 );
2267 QVariantAnimation *animation =
new QVariantAnimation(
this );
2268 connect( animation, &QVariantAnimation::finished,
this, [animation, rb]
2270 animation->deleteLater();
2273 connect( animation, &QPropertyAnimation::valueChanged,
this, [rb, geomType](
const QVariant & value )
2275 QColor
c = value.value<QColor>();
2284 c.setAlpha(
c.alpha() );
2290 animation->setDuration( duration * flashes );
2291 animation->setStartValue( endColor );
2292 double midStep = 0.2 / flashes;
2293 for (
int i = 0; i < flashes; ++i )
2295 double start =
static_cast< double >( i ) / flashes;
2296 animation->setKeyValueAt( start + midStep, startColor );
2297 double end =
static_cast< double >( i + 1 ) / flashes;
2299 animation->setKeyValueAt( end, endColor );
2301 animation->setEndValue( endColor );
2324 if ( !e->isAccepted() )
2329 double dx = std::fabs( currentExtent.
width() / 4 );
2330 double dy = std::fabs( currentExtent.
height() / 4 );
2362 if ( ! e->isAutoRepeat() )
2370 case Qt::Key_PageUp:
2375 case Qt::Key_PageDown:
2382 mUseParallelRendering = !mUseParallelRendering;
2387 mDrawRenderingStats = !mDrawRenderingStats;
2415 mTemporaryCursorOverride.reset();
2429 QgsDebugMsgLevel(
"Ignoring key release: " + QString::number( e->key() ), 2 );
2448void QgsMapCanvas::beginZoomRect( QPoint pos )
2450 mZoomRect.setRect( 0, 0, 0, 0 );
2452 mZoomDragging =
true;
2454 QColor color( Qt::blue );
2455 color.setAlpha( 63 );
2456 mZoomRubberBand->setColor( color );
2457 mZoomRect.setTopLeft( pos );
2460void QgsMapCanvas::stopZoomRect()
2462 if ( mZoomDragging )
2464 mZoomDragging =
false;
2465 mZoomRubberBand.reset(
nullptr );
2466 mTemporaryCursorOverride.reset();
2470void QgsMapCanvas::endZoomRect( QPoint pos )
2475 mZoomRect.setRight( pos.x() );
2476 mZoomRect.setBottom( pos.y() );
2479 mZoomRect = mZoomRect.normalized();
2481 if ( mZoomRect.width() < 5 && mZoomRect.height() < 5 )
2488 const QSize &zoomRectSize = mZoomRect.size();
2489 const QSize &canvasSize = mSettings.
outputSize();
2490 double sfx =
static_cast< double >( zoomRectSize.width() ) / canvasSize.width();
2491 double sfy =
static_cast< double >( zoomRectSize.height() ) / canvasSize.height();
2492 double sf = std::max( sfx, sfy );
2500void QgsMapCanvas::startPan()
2510void QgsMapCanvas::stopPan()
2515 mTemporaryCursorOverride.reset();
2523 if ( e->button() == Qt::MiddleButton &&
2524 e->modifiers() & Qt::ShiftModifier )
2526 beginZoomRect( e->pos() );
2530 else if ( e->button() == Qt::MiddleButton )
2545 && e->modifiers() & Qt::ShiftModifier )
2547 beginZoomRect( e->pos() );
2553 showContextMenu( me.get() );
2576 if ( mZoomDragging &&
2577 e->button() == Qt::MiddleButton )
2579 endZoomRect( e->pos() );
2583 else if ( e->button() == Qt::MiddleButton )
2587 else if ( e->button() == Qt::BackButton )
2592 else if ( e->button() == Qt::ForwardButton )
2599 if ( mZoomDragging && e->button() == Qt::LeftButton )
2601 endZoomRect( e->pos() );
2623 QGraphicsView::resizeEvent( e );
2624 mResizeTimer->start( 500 );
2626 double oldScale = mSettings.
scale();
2627 QSize lastSize = viewport()->size();
2630 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
2636 double scaleFactor = oldScale / mSettings.
scale();
2654 QGraphicsView::paintEvent( e );
2659 if ( mBlockItemPositionUpdates )
2662 const QList<QGraphicsItem *> items = mScene->items();
2663 for ( QGraphicsItem *gi : items )
2680 QgsDebugMsgLevel(
"Wheel event delta " + QString::number( e->angleDelta().y() ), 2 );
2685 if ( e->isAccepted() )
2689 if ( e->angleDelta().y() == 0 )
2696 bool reverseZoom = settings.
value( QStringLiteral(
"qgis/reverse_wheel_zoom" ),
false ).toBool();
2697 bool zoomIn = reverseZoom ? e->angleDelta().y() < 0 : e->angleDelta().y() > 0;
2701 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( e->angleDelta().y() );
2703 if ( e->modifiers() & Qt::ControlModifier )
2706 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
2709 double signedWheelFactor =
zoomIn ? 1 / zoomFactor : zoomFactor;
2714 QgsPointXY newCenter( mousePos.
x() + ( ( oldCenter.
x() - mousePos.
x() ) * signedWheelFactor ),
2715 mousePos.
y() + ( ( oldCenter.
y() - mousePos.
y() ) * signedWheelFactor ) );
2723 mWheelZoomFactor = std::max( factor, 1.01 );
2752 ScaleRestorer restorer(
this );
2763 if ( mScaleLocked != isLocked )
2765 mScaleLocked = isLocked;
2778 else if ( mZoomDragging )
2780 mZoomRect.setBottomRight( e->pos() );
2781 mZoomRubberBand->setToCanvasRectangle( mZoomRect );
2782 mZoomRubberBand->show();
2795 if ( !panOperationInProgress() )
2807 if ( tool == mMapTool )
2818 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2829 connect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2837 if ( mMapTool && mMapTool == tool )
2839 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2844 setCursor( Qt::ArrowCursor );
2868 QBrush bgBrush( color );
2869 setBackgroundBrush( bgBrush );
2872 palette.setColor( backgroundRole(), color );
2873 setPalette( palette );
2877 mScene->setBackgroundBrush( bgBrush );
2886 return mScene->backgroundBrush().color();
2898 bool hasSelectedFeatures =
false;
2905 hasSelectedFeatures =
true;
2910 if ( hasSelectedFeatures )
2976 if ( mTheme ==
theme )
2990 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
3008void QgsMapCanvas::connectNotify(
const char *signal )
3015void QgsMapCanvas::layerRepaintRequested(
bool deferred )
3021void QgsMapCanvas::autoRefreshTriggered()
3027 mRefreshAfterJob =
true;
3034void QgsMapCanvas::updateAutoRefreshTimer()
3038 int minAutoRefreshInterval = -1;
3042 int layerRefreshInterval = 0;
3053 if ( rendererRefreshRate > 0 )
3055 layerRefreshInterval = 1000 / rendererRefreshRate;
3060 if ( layerRefreshInterval == 0 )
3063 minAutoRefreshInterval = minAutoRefreshInterval > 0 ? std::min( layerRefreshInterval, minAutoRefreshInterval ) : layerRefreshInterval;
3066 if ( minAutoRefreshInterval > 0 )
3068 mAutoRefreshTimer.setInterval( minAutoRefreshInterval );
3069 mAutoRefreshTimer.start();
3073 mAutoRefreshTimer.stop();
3077void QgsMapCanvas::projectThemesChanged()
3079 if ( mTheme.isEmpty() )
3110 double dx = end.
x() - start.
x();
3111 double dy = end.
y() - start.
y();
3113 c.set(
c.x() - dx,
c.y() - dy );
3151 setSceneRect( -pnt.x(), -pnt.y(), viewport()->size().width(), viewport()->size().height() );
3159 bool allHandled =
true;
3162 bool handled =
false;
3165 if ( handler && handler->customUriProviderKey() == uri.providerKey )
3167 if ( handler->handleCustomUriCanvasDrop( uri,
this ) )
3191 updateDevicePixelFromScreen();
3196 if ( !mBlockExtentChangedSignal )
3207 if ( !mPreviewEffect )
3212 mPreviewEffect->setEnabled( previewEnabled );
3217 if ( !mPreviewEffect )
3222 return mPreviewEffect->isEnabled();
3227 if ( !mPreviewEffect )
3232 mPreviewEffect->
setMode( mode );
3237 if ( !mPreviewEffect )
3242 return mPreviewEffect->
mode();
3247 if ( !mSnappingUtils )
3253 return mSnappingUtils;
3258 mSnappingUtils = utils;
3265 QDomNodeList nodes = doc.elementsByTagName( QStringLiteral(
"mapcanvas" ) );
3266 if ( nodes.count() )
3268 QDomNode node = nodes.item( 0 );
3271 if ( nodes.count() > 1 )
3273 for (
int i = 0; i < nodes.size(); ++i )
3275 QDomElement elementNode = nodes.at( i ).toElement();
3277 if ( elementNode.hasAttribute( QStringLiteral(
"name" ) ) && elementNode.attribute( QStringLiteral(
"name" ) ) == objectName() )
3279 node = nodes.at( i );
3287 if ( objectName() != QLatin1String(
"theMapCanvas" ) )
3298 QDomElement elem = node.toElement();
3299 if ( elem.hasAttribute( QStringLiteral(
"theme" ) ) )
3301 if (
QgsProject::instance()->mapThemeCollection()->hasMapTheme( elem.attribute( QStringLiteral(
"theme" ) ) ) )
3303 setTheme( elem.attribute( QStringLiteral(
"theme" ) ) );
3306 setAnnotationsVisible( elem.attribute( QStringLiteral(
"annotationsVisible" ), QStringLiteral(
"1" ) ).toInt() );
3309 const QDomNodeList scopeElements = elem.elementsByTagName( QStringLiteral(
"expressionContextScope" ) );
3310 if ( scopeElements.size() > 0 )
3312 const QDomElement scopeElement = scopeElements.at( 0 ).toElement();
3318 QgsDebugMsgLevel( QStringLiteral(
"Couldn't read mapcanvas information from project" ), 2 );
3333 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
3336 QgsDebugError( QStringLiteral(
"Unable to find qgis element in project file" ) );
3339 QDomNode qgisNode = nl.item( 0 );
3341 QDomElement mapcanvasNode = doc.createElement( QStringLiteral(
"mapcanvas" ) );
3342 mapcanvasNode.setAttribute( QStringLiteral(
"name" ), objectName() );
3343 if ( !mTheme.isEmpty() )
3344 mapcanvasNode.setAttribute( QStringLiteral(
"theme" ), mTheme );
3345 mapcanvasNode.setAttribute( QStringLiteral(
"annotationsVisible" ), mAnnotationsVisible );
3346 qgisNode.appendChild( mapcanvasNode );
3348 mSettings.
writeXml( mapcanvasNode, doc );
3351 QDomElement scopeElement = doc.createElement( QStringLiteral(
"expressionContextScope" ) );
3353 tmpScope.
removeVariable( QStringLiteral(
"atlas_featurenumber" ) );
3359 mapcanvasNode.appendChild( scopeElement );
3366 if ( mScaleLocked && !ignoreScaleLock )
3368 ScaleRestorer restorer(
this );
3403 bool allHandled =
true;
3406 bool handled =
false;
3409 if ( handler->canHandleCustomUriCanvasDrop( uri,
this ) )
3435 return QGraphicsView::viewportEvent(
event );
3438void QgsMapCanvas::mapToolDestroyed()
3446 if ( e->type() == QEvent::Gesture )
3448 if ( QTapAndHoldGesture *tapAndHoldGesture = qobject_cast< QTapAndHoldGesture * >(
static_cast<QGestureEvent *
>( e )->gesture( Qt::TapAndHoldGesture ) ) )
3450 QPointF pos = tapAndHoldGesture->position();
3451 pos = mapFromGlobal( QPoint( pos.x(), pos.y() ) );
3459 return mMapTool->
gestureEvent(
static_cast<QGestureEvent *
>( e ) );
3464 return QGraphicsView::event( e );
3490 while ( mRefreshScheduled || mJob )
3492 QgsApplication::processEvents();
3508 QList<QgsMapCanvasAnnotationItem *> annotationItemList;
3509 const QList<QGraphicsItem *> items = mScene->items();
3510 for ( QGraphicsItem *gi : items )
3515 annotationItemList.push_back( aItem );
3519 return annotationItemList;
3524 mAnnotationsVisible = show;
3528 item->setVisible( show );
3542void QgsMapCanvas::startPreviewJobs()
3551 schedulePreviewJob( 0 );
3554void QgsMapCanvas::startPreviewJob(
int number )
3567 double dx = ( i - 1 ) * mapRect.
width();
3568 double dy = ( 1 - j ) * mapRect.
height();
3583 const QList<QgsMapLayer *>
layers = jobSettings.
layers();
3584 QList< QgsMapLayer * > previewLayers;
3589 if (
layer->
customProperty( QStringLiteral(
"rendering/noPreviewJobs" ),
false ).toBool() )
3591 QgsDebugMsgLevel( QStringLiteral(
"Layer %1 not rendered because it is explicitly blocked from preview jobs" ).arg(
layer->
id() ), 3 );
3598 QgsDebugMsgLevel( QStringLiteral(
"Layer %1 not rendered because it does not match the renderInPreview criterion %2" ).arg(
layer->
id() ).arg( mLastLayerRenderTime.value(
layer->
id() ) ), 3 );
3602 previewLayers <<
layer;
3612 job->setProperty(
"number", number );
3613 mPreviewJobs.append( job );
3618void QgsMapCanvas::stopPreviewJobs()
3620 mPreviewTimer.stop();
3621 for (
auto previewJob = mPreviewJobs.constBegin(); previewJob != mPreviewJobs.constEnd(); ++previewJob )
3627 ( *previewJob )->cancelWithoutBlocking();
3630 mPreviewJobs.clear();
3633void QgsMapCanvas::schedulePreviewJob(
int number )
3635 mPreviewTimer.setSingleShot(
true );
3636 mPreviewTimer.setInterval( PREVIEW_JOB_DELAY_MS );
3637 disconnect( mPreviewTimerConnection );
3638 mPreviewTimerConnection = connect( &mPreviewTimer, &QTimer::timeout,
this, [ = ]()
3640 startPreviewJob( number );
3642 mPreviewTimer.start();
3645bool QgsMapCanvas::panOperationInProgress()
3650 if (
QgsMapToolPan *panTool = qobject_cast< QgsMapToolPan *>( mMapTool ) )
3652 if ( panTool->isDragging() )
3659int QgsMapCanvas::nextZoomLevel(
const QList<double> &resolutions,
bool zoomIn )
const
3661 int resolutionLevel = -1;
3663 int nResolutions = resolutions.size();
3665 for (
int i = 0; i < nResolutions; ++i )
3667 if (
qgsDoubleNear( resolutions[i], currentResolution, 0.0001 ) )
3669 resolutionLevel =
zoomIn ? ( i - 1 ) : ( i + 1 );
3672 else if ( currentResolution <= resolutions[i] )
3674 resolutionLevel =
zoomIn ? ( i - 1 ) : i;
3677 resolutionLevel =
zoomIn ? i : i + 1;
3680 if ( resolutionLevel < 0 || resolutionLevel >= nResolutions )
3684 if (
zoomIn && resolutionLevel == nResolutions - 1 && resolutions[nResolutions - 1] < currentResolution / mWheelZoomFactor )
3689 if ( !
zoomIn && resolutionLevel == 0 && resolutions[0] > mWheelZoomFactor * currentResolution )
3694 return resolutionLevel;
3699 if ( !mZoomResolutions.isEmpty() )
3701 int zoomLevel = nextZoomLevel( mZoomResolutions,
true );
3702 if ( zoomLevel != -1 )
3707 return 1 / mWheelZoomFactor;
3712 if ( !mZoomResolutions.isEmpty() )
3714 int zoomLevel = nextZoomLevel( mZoomResolutions,
false );
3715 if ( zoomLevel != -1 )
3720 return mWheelZoomFactor;
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.
@ 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.
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.
@ 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.
@ MaximumAngle
Maximum angle between generating radii (lines from arc center to output vertices)
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.
This class represents a coordinate reference system (CRS).
QString userFriendlyIdentifier(Qgis::CrsIdentifierType type=Qgis::CrsIdentifierType::MediumString) const
Returns a user friendly identifier for the CRS.
void updateDefinition()
Updates the definition and parameters of the coordinate reference system to their latest values.
QList< Qgis::CrsAxisDirection > axisOrdering() const
Returns an ordered list of the axis directions reflecting the native axis order for the CRS.
Qgis::DistanceUnit mapUnits
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.
Abstract base class for spatial data provider implementations.
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.
double bearing(const QgsPointXY &p1, const QgsPointXY &p2) const
Computes the bearing (in radians) between two points.
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
Qgis::DistanceUnit lengthUnits() const
Returns the units of distance for length calculations made by this object.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
QgsRange which stores a range of double values.
bool isActive() const
Returns whether this shading renderer is active.
Abstract interface for generating an expression context scope.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads scope variables from an XML element.
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.
Abstract base class for all 2D vector feature renderers.
This class 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.
A map layer which consists of a set of child layers, where all component layers are rendered as a sin...
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.
Class that 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.
Map canvas is a class for displaying all GIS data types on a canvas.
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)
Freeze/thaw 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.
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)
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.
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.
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 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 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 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.
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)
virtual QgsMapLayerElevationProperties::Flags flags() const
Returns flags associated to the elevation properties.
@ FlagDontInvalidateCachedRendersWhenRangeChanges
Any cached rendering will not be invalidated when z range context is modified.
virtual bool hasElevation() const
Returns true if the layer has an elevation or z component.
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.
virtual bool isSpatial() const
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
void autoRefreshIntervalChanged(int interval)
Emitted when the auto refresh interval changes.
QgsCoordinateReferenceSystem crs
Q_DECL_DEPRECATED bool hasAutoRefreshEnabled() const
Returns true if auto refresh is enabled for the layer.
void rendererChanged()
Signal emitted when renderer is changed.
virtual QgsMapLayerTemporalProperties * temporalProperties()
Returns the layer's temporal properties.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
virtual QgsMapLayerElevationProperties * elevationProperties()
Returns the layer's elevation properties.
virtual Q_INVOKABLE QgsDataProvider * dataProvider()
Returns the layer's data provider, it may be nullptr.
virtual Q_INVOKABLE void reload()
Synchronises with changes in the datasource.
A QgsMapMouseEvent is the result of a user interaction with the mouse on a QgsMapCanvas.
This class is responsible for keeping cache of rendered images resulting from a map rendering job.
void clear()
Invalidates the cache contents, clearing all cached images.
void invalidateCacheForLayer(QgsMapLayer *layer)
Invalidates cached images which relate to the specified map layer.
void clearCacheImage(const QString &cacheKey)
Removes an image from the cache with matching cacheKey.
Job implementation that renders everything sequentially using a custom painter.
void waitForFinished() override
Block until the job has finished.
virtual void waitForFinished()=0
Block until the job has finished.
void setCache(QgsMapRendererCache *cache)
Assign a cache to be used for reading and storing rendered images of individual layers.
QHash< QgsMapLayer *, int > perLayerRenderingTime() const
Returns the render time (in ms) per layer.
virtual bool usedCachedLabels() const =0
Returns true if the render job was able to use a cached labeling solution.
Errors errors() const
List of errors that happened during the rendering job - available when the rendering has been finishe...
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.
int renderingTime() const
Returns the total time it took to finish the job (in milliseconds).
QStringList layersRedrawnFromCache() const
Returns a list of the layer IDs for all layers which were redrawn from cached images.
QList< QgsMapRendererJob::Error > Errors
QgsRenderedItemResults * takeRenderedItemResults()
Takes the rendered item results from the map render job and returns them.
virtual bool isActive() const =0
Tell whether the rendering job is currently running in background.
virtual QgsLabelingResults * takeLabelingResults()=0
Gets pointer to internal labeling engine (in order to get access to the results).
virtual void cancel()=0
Stop the rendering job - does not return until the job has terminated.
void setLayerRenderingTimeHints(const QHash< QString, int > &hints)
Sets approximate render times (in ms) for map layers.
virtual void cancelWithoutBlocking()=0
Triggers cancellation of the rendering job without blocking.
Job implementation that renders all layers in parallel.
Intermediate base class adding functionality that allows client to query the rendered image.
virtual QImage renderedImage()=0
Gets a preview/resulting image.
Job implementation that renders everything sequentially in one thread.
static QString worldFileContent(const QgsMapSettings &mapSettings)
Creates the content of a world file.
The QgsMapSettings class contains configuration for rendering of the map.
void setElevationShadingRenderer(const QgsElevationShadingRenderer &renderer)
Sets the shading renderer used to render shading on the entire map.
Qgis::DistanceUnit mapUnits() const
Returns the units of the map's geographical coordinates - used for scale calculation.
void writeXml(QDomNode &node, QDomDocument &doc)
Writes the map settings to an XML node.
QgsPointXY layerToMapCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from layer's CRS to output CRS
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
QList< QgsMapLayer * > layers(bool expandGroupLayers=false) const
Returns the list of layers which will be rendered in the map.
void setSelectionColor(const QColor &color)
Sets the color that is used for drawing of selected vector features.
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.
void setFlags(Qgis::MapSettingsFlags flags)
Sets combination of flags that will be used for rendering.
QgsRectangle layerExtentToOutputExtent(const QgsMapLayer *layer, QgsRectangle extent) const
transform bounding box from layer's CRS to output CRS
QgsDoubleRange zRange() const
Returns the range of z-values which will be visible in the map.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
void setDpiTarget(double dpi)
Sets the target dpi (dots per inch) to be taken into consideration when rendering.
double magnificationFactor() const
Returns the magnification factor.
QStringList layerIds(bool expandGroupLayers=false) const
Returns the list of layer IDs which will be rendered in the map.
void setDevicePixelRatio(float dpr)
Sets the device pixel ratio.
void setZRange(const QgsDoubleRange &range)
Sets the range of z-values which will be visible in the map.
QColor backgroundColor() const
Returns the background color of the map.
void setOutputDpi(double dpi)
Sets the dpi (dots per inch) used for conversion between real world units (e.g.
const QgsMapToPixel & mapToPixel() const
double mapUnitsPerPixel() const
Returns the distance in geographical coordinates that equals to one pixel in the map.
void setRendererUsage(Qgis::RendererUsage rendererUsage)
Sets the rendering usage.
float devicePixelRatio() const
Returns the device pixel ratio.
QSize outputSize() const
Returns the size of the resulting map image, in pixels.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the map of map layer style overrides (key: layer ID, value: style name) where a different style ...
void setExtent(const QgsRectangle &rect, bool magnified=true)
Sets the coordinates of the rectangle which should be rendered.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
QColor selectionColor() const
Returns the color that is used for drawing of selected vector features.
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes output image size into account.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets the global configuration of the labeling engine.
QgsRectangle fullExtent() const
returns current extent of layer set
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the coordinate transform context, which stores various information regarding which datum transfo...
void setRotation(double rotation)
Sets the rotation of the resulting map image, in degrees clockwise.
void setCurrentFrame(long long frame)
Sets the current frame of the map, for maps which are part of an animation.
const QgsElevationShadingRenderer & elevationShadingRenderer() const
Returns the shading renderer used to render shading on the entire map.
void setPathResolver(const QgsPathResolver &resolver)
Sets the path resolver for conversion between relative and absolute paths during rendering operations...
bool testFlag(Qgis::MapSettingsFlag flag) const
Check whether a particular flag is enabled.
QMap< QString, QString > layerStyleOverrides() const
Returns the map of map layer style overrides (key: layer ID, value: style name) where a different sty...
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
bool hasValidSettings() const
Check whether the map settings are valid and can be used for rendering.
void setOutputSize(QSize size)
Sets the size of the resulting map image, in pixels.
QgsPointXY mapToLayerCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from output CRS to layer's CRS
void setBackgroundColor(const QColor &color)
Sets the background color of the map.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
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 setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Sets the destination crs (coordinate reference system) for the map render.
void readXml(QDomNode &node)
Restore the map settings from a XML node.
void setMagnificationFactor(double factor, const QgsPointXY *center=nullptr)
Set the magnification factor.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
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.
bool hasMapTheme(const QString &name) const
Returns whether a map theme with a matching name exists.
QMap< QString, QString > mapThemeStyleOverrides(const QString &name)
Gets layer style overrides (for QgsMapSettings) of the visible layers for given map theme.
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.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
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 class to represent a 2D point.
double sqrDist(double x, double y) const
Returns the squared distance between this point a specified x, y coordinate.
A graphics effect which can be applied to a widget to simulate various printing and color blindness m...
void setMode(PreviewMode mode)
Sets the mode for the preview effect, which controls how the effect modifies a widgets appearance.
PreviewMode mode() const
Returns the mode used for the preview effect.
double defaultRotation() const
Returns the default map rotation (in clockwise degrees) for maps in the project.
QgsReferencedRectangle defaultViewExtent() const
Returns the default view extent, which should be used as the initial map extent when this project is ...
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.
QgsPathResolver pathResolver() const
Returns path resolver object with considering whether the project uses absolute or relative paths and...
QgsAnnotationLayer * mainAnnotationLayer()
Returns the main annotation layer associated with the project.
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
QgsMapThemeCollection * mapThemeCollection
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
QgsCoordinateTransformContext transformContext
QgsElevationShadingRenderer elevationShadingRenderer() const
Returns the elevation shading renderer used for map shading.
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 generic dialog to prompt the user for a Coordinate Reference System.
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
void setYMinimum(double y)
Set the minimum y value.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
void setXMinimum(double x)
Set the minimum x value.
double width() const
Returns the width of the rectangle.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
bool isNull() const
Test if the rectangle is null (holding no spatial information).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
void setYMaximum(double y)
Set the maximum y value.
QgsPointXY center() const
Returns the center point of the rectangle.
void setXMaximum(double x)
Set the maximum x value.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
bool isEmpty() const
Returns true if the rectangle has no area.
double height() const
Returns the height of the rectangle.
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.
void transferResults(QgsRenderedItemResults *other, const QStringList &layerIds)
Transfers all results from an other QgsRenderedItemResults object where the items have layer IDs matc...
A class 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.
static const QgsSettingsEntryBool * settingsRespectScreenDPI
Settings entry respect screen dpi.
This class is a composition of two QSettings instances:
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
T enumValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on an enum.
This class has all the configuration of snapping and can return answers to snapping queries.
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.
bool isActive() const
Returns true if the temporal property is active.
virtual QgsTemporalProperty::Flags flags() const
Returns flags associated to the temporal property.
@ FlagDontInvalidateCachedRendersWhenRangeChanges
Any cached rendering will not be invalidated when temporal range context is modified.
const QgsDateTimeRange & temporalRange() const
Returns the datetime range for the object.
void setIsTemporal(bool enabled)
Sets whether the temporal range is enabled (i.e.
void setTemporalRange(const QgsDateTimeRange &range)
Sets the temporal range for the object.
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 data sets.
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.
A class to represent a 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)
const QgsCoordinateReferenceSystem & crs
Stores settings related to the context in which a preview job runs.
double maxRenderingTimeMs
Default maximum allowable render time, in ms.
double lastRenderingTimeMs
Previous rendering time for the layer, in ms.