QGIS API Documentation
3.14.0-Pi (9f7028fd23)
|
Go to the documentation of this file.
21 #include <QApplication>
25 #include <QGraphicsItem>
26 #include <QGraphicsScene>
27 #include <QGraphicsView>
30 #include <QPaintEvent>
33 #include <QTextStream>
34 #include <QResizeEvent>
37 #include <QStringList>
38 #include <QWheelEvent>
118 : QGraphicsView( parent )
120 , mMenu( new QMenu( this ) )
121 , mExpressionContextScope( tr(
"Map Canvas" ) )
123 mScene =
new QGraphicsScene();
125 setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
126 setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
127 setMouseTracking(
true );
128 setFocusPolicy( Qt::StrongFocus );
130 mResizeTimer =
new QTimer(
this );
131 mResizeTimer->setSingleShot(
true );
134 mRefreshTimer =
new QTimer(
this );
135 mRefreshTimer->setSingleShot(
true );
136 connect( mRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::refreshMap );
139 mMap =
new QgsMapCanvasMap(
this );
168 emit transformContextChanged();
181 double segmentationTolerance = settings.
value( QStringLiteral(
"qgis/segmentationTolerance" ),
"0.01745" ).toDouble();
183 mSettings.setSegmentationTolerance( segmentationTolerance );
184 mSettings.setSegmentationToleranceType( toleranceType );
186 mWheelZoomFactor = settings.
value( QStringLiteral(
"qgis/zoom_factor" ), 2 ).toDouble();
188 QSize s = viewport()->size();
189 mSettings.setOutputSize( s );
190 mSettings.setDevicePixelRatio( devicePixelRatio() );
191 setSceneRect( 0, 0, s.width(), s.height() );
192 mScene->setSceneRect( QRectF( 0, 0, s.width(), s.height() ) );
194 moveCanvasContents(
true );
197 if ( window()->windowHandle() )
199 connect( window()->windowHandle(), &QWindow::screenChanged,
this, [ = ]( QScreen * ) {mSettings.setDevicePixelRatio( devicePixelRatio() );} );
200 connect( window()->windowHandle()->screen(), &QScreen::physicalDotsPerInchChanged,
this, [ = ]( qreal ) {mSettings.setDevicePixelRatio( devicePixelRatio() );} );
203 connect( &mMapUpdateTimer, &QTimer::timeout,
this, &QgsMapCanvas::mapUpdateTimeout );
204 mMapUpdateTimer.setInterval( 250 );
209 grabGesture( Qt::PinchGesture );
210 grabGesture( Qt::TapAndHoldGesture );
211 viewport()->setAttribute( Qt::WA_AcceptTouchEvents );
215 viewport()->setGraphicsEffect( mPreviewEffect );
219 connect( &mAutoRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::autoRefreshTriggered );
223 setInteractive(
false );
227 setCanvasColor( mSettings.backgroundColor() );
229 setTemporalRange( mSettings.temporalRange() );
242 mLastNonZoomMapTool =
nullptr;
252 QList< QgsMapRendererQImageJob * >::const_iterator previewJob = mPreviewJobs.constBegin();
253 for ( ; previewJob != mPreviewJobs.constEnd(); ++previewJob )
265 qDeleteAll( mScene->items() );
267 mScene->deleteLater();
270 delete mLabelingResults;
278 factor = qBound( magnifierMin, factor, magnifierMax );
307 if ( index >= 0 && index <
layers.size() )
315 if ( mCurrentLayer ==
layer )
318 mCurrentLayer =
layer;
329 return nullptr != mJob;
342 if ( !mTheme.isEmpty() )
345 setLayersPrivate(
layers );
348 void QgsMapCanvas::setLayersPrivate(
const QList<QgsMapLayer *> &layers )
350 QList<QgsMapLayer *> oldLayers = mSettings.
layers();
353 if (
layers == oldLayers )
356 const auto constOldLayers = oldLayers;
369 const auto constLayers =
layers;
385 updateAutoRefreshTimer();
413 QgsDebugMsg( QStringLiteral(
"Transform error caught: %1" ).arg( e.
what() ) );
425 QgsDebugMsgLevel( QStringLiteral(
"refreshing after destination CRS changed" ), 2 );
436 mController = controller;
454 return mLabelingResults;
481 return nullptr != mCache;
492 mUseParallelRendering = enabled;
497 return mUseParallelRendering;
502 mMapUpdateTimer.setInterval( timeMilliseconds );
507 return mMapUpdateTimer.interval();
513 return mCurrentLayer;
528 QgsDebugMsgLevel( QStringLiteral(
"CANVAS refresh - invalid settings -> nothing to do" ), 2 );
532 if ( !mRenderFlag || mFrozen )
538 if ( mRefreshScheduled )
540 QgsDebugMsgLevel( QStringLiteral(
"CANVAS refresh already scheduled" ), 2 );
544 mRefreshScheduled =
true;
549 mRefreshTimer->start( 1 );
552 void QgsMapCanvas::refreshMap()
554 Q_ASSERT( mRefreshScheduled );
569 expressionContext << generator->createExpressionContextScope();
577 if ( !mTheme.isEmpty() )
590 mJobCanceled =
false;
591 if ( mUseParallelRendering )
606 mRefreshScheduled =
false;
608 mMapUpdateTimer.start();
613 void QgsMapCanvas::mapThemeChanged(
const QString &theme )
615 if (
theme == mTheme )
620 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
633 void QgsMapCanvas::mapThemeRenamed(
const QString &theme,
const QString &newTheme )
635 if ( mTheme.isEmpty() ||
theme != mTheme )
644 void QgsMapCanvas::rendererJobFinished()
646 QgsDebugMsgLevel( QStringLiteral(
"CANVAS finish! %1" ).arg( !mJobCanceled ), 2 );
648 mMapUpdateTimer.stop();
651 const auto constErrors = mJob->
errors();
665 delete mLabelingResults;
676 if ( settings.
value( QStringLiteral(
"Map/logCanvasRefreshEvent" ),
false ).toBool() )
678 QString logMsg = tr(
"Canvas refresh: %1 ms" ).arg( mJob->
renderingTime() );
682 if ( mDrawRenderingStats )
684 int w = img.width(), h = img.height();
685 QFont fnt = p.font();
688 int lh = p.fontMetrics().height() * 2;
689 QRect r( 0, h - lh, w, lh );
690 p.setPen( Qt::NoPen );
691 p.setBrush( QColor( 0, 0, 0, 110 ) );
693 p.setPen( Qt::white );
694 QString msg = QStringLiteral(
"%1 :: %2 ms" ).arg( mUseParallelRendering ? QStringLiteral(
"PARALLEL" ) : QStringLiteral(
"SEQUENTIAL" ) ).arg( mJob->
renderingTime() );
695 p.drawText( r, msg, QTextOption( Qt::AlignCenter ) );
700 mMap->setContent( img, imageRect( img, mSettings ) );
702 mLastLayerRenderTime.clear();
704 for (
auto it = times.constBegin(); it != times.constEnd(); ++it )
706 mLastLayerRenderTime.insert( it.key()->id(), it.value() );
708 if ( mUsePreviewJobs && !mRefreshAfterJob )
713 mRefreshAfterJob =
false;
723 if ( mRefreshAfterJob )
725 mRefreshAfterJob =
false;
726 clearTemporalCache();
731 void QgsMapCanvas::previewJobFinished()
739 mPreviewJobs.removeAll( job );
741 int number = job->property(
"number" ).toInt();
744 startPreviewJob( number + 1 );
761 QgsLogger::warning( QStringLiteral(
"The renderer map has a wrong device pixel ratio" ) );
765 QgsRectangle rect( topLeft.
x(), topLeft.
y(), topLeft.
x() + img.width()*res, topLeft.
y() - img.height()*res );
771 return mUsePreviewJobs;
776 mUsePreviewJobs = enabled;
781 mDropHandlers = handlers;
784 void QgsMapCanvas::clearTemporalCache()
804 const QgsPointXY mapPoint =
event->originalMapPoint();
808 QMenu *copyCoordinateMenu =
new QMenu( tr(
"Copy Coordinate" ), mMenu );
816 const QgsPointXY transformedPoint = ct.transform( mapPoint );
819 int displayPrecision = 0;
825 displayPrecision = 0;
827 displayPrecision = 1;
829 displayPrecision = 2;
831 displayPrecision = 3;
833 displayPrecision = 4;
835 displayPrecision = 5;
837 displayPrecision = 6;
839 displayPrecision = 7;
841 displayPrecision = 8;
843 displayPrecision = 9;
850 QAction *copyCoordinateAction =
new QAction( QStringLiteral(
"%3 (%1, %2)" ).arg(
851 QString::number( transformedPoint.
x(),
'f', displayPrecision ),
852 QString::number( transformedPoint.
y(),
'f', displayPrecision ),
853 identifier ), mMenu );
855 connect( copyCoordinateAction, &QAction::triggered,
this, [displayPrecision, transformedPoint]
857 QClipboard *clipboard = QApplication::clipboard();
859 const QString coordinates = QString::number( transformedPoint.
x(),
'f', displayPrecision ) +
',' + QString::number( transformedPoint.
y(),
'f', displayPrecision );
862 if ( clipboard->supportsSelection() )
864 clipboard->setText( coordinates, QClipboard::Selection );
866 clipboard->setText( coordinates, QClipboard::Clipboard );
869 copyCoordinateMenu->addAction( copyCoordinateAction );
882 const QString customCrsString = settings.
value( QStringLiteral(
"qgis/custom_coordinate_crs" ) ).toString();
883 if ( !customCrsString.isEmpty() )
891 copyCoordinateMenu->addSeparator();
892 QAction *setCustomCrsAction =
new QAction( tr(
"Set Custom CRS…" ), mMenu );
893 connect( setCustomCrsAction, &QAction::triggered,
this, [ = ]
897 if ( selector.exec() )
902 copyCoordinateMenu->addAction( setCustomCrsAction );
904 mMenu->addMenu( copyCoordinateMenu );
909 mMenu->exec(
event->globalPos() );
918 mSettings.
setIsTemporal( dateTimeRange.begin().isValid() || dateTimeRange.end().isValid() );
925 clearTemporalCache();
927 autoRefreshTriggered();
937 mInteractionBlockers.append( blocker );
942 mInteractionBlockers.removeAll( blocker );
949 if ( block->blockCanvasInteraction( interaction ) )
955 void QgsMapCanvas::mapUpdateTimeout()
960 mMap->setContent( img, imageRect( img, mSettings ) );
989 image = theQPixmap->toImage();
990 painter.begin( &image );
1000 image = mMap->contentImage().copy();
1001 painter.begin( &image );
1005 QStyleOptionGraphicsItem option;
1006 option.initFrom(
this );
1007 QGraphicsItem *item =
nullptr;
1008 QListIterator<QGraphicsItem *> i( items() );
1010 while ( i.hasPrevious() )
1012 item = i.previous();
1021 QPointF itemScenePos = item->scenePos();
1022 painter.translate( itemScenePos.x(), itemScenePos.y() );
1024 item->paint( &painter, &option );
1030 image.save( fileName, format.toLocal8Bit().data() );
1032 QFileInfo myInfo = QFileInfo( fileName );
1035 QString outputSuffix = myInfo.suffix();
1036 QString myWorldFileName = myInfo.absolutePath() +
'/' + myInfo.completeBaseName() +
'.'
1037 + outputSuffix.at( 0 ) + outputSuffix.at( myInfo.suffix().size() - 1 ) +
'w';
1038 QFile myWorldFile( myWorldFileName );
1039 if ( !myWorldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
1043 QTextStream myStream( &myWorldFile );
1064 if ( ( r == current ) && magnified )
1077 QgsDebugMsgLevel( QStringLiteral(
"Empty extent - keeping old scale with new center!" ), 2 );
1086 if ( mLastExtent.size() > 20 )
1087 mLastExtent.removeAt( 0 );
1090 for (
int i = mLastExtent.size() - 1; i > mLastExtentIndex; i-- )
1092 mLastExtent.removeAt( i );
1095 mLastExtent.append(
extent() );
1098 if ( mLastExtent.size() > 20 )
1100 mLastExtent.removeAt( 0 );
1104 mLastExtentIndex = mLastExtent.size() - 1;
1155 return mCursorPoint;
1199 if ( mLastExtentIndex > 0 )
1202 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
1215 if ( mLastExtentIndex < mLastExtent.size() - 1 )
1218 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
1230 mLastExtent.clear();
1231 mLastExtent.append(
extent() ) ;
1232 mLastExtentIndex = mLastExtent.size() - 1;
1243 layer = qobject_cast<QgsVectorLayer *>( mCurrentLayer );
1262 int scaleFactor = 5;
1270 double closestSquaredDistance = pow( extentRect.
width(), 2.0 ) + pow( extentRect.
height(), 2.0 );
1271 bool pointFound =
false;
1275 double sqrDist = point.
sqrDist( centerLayerCoordinates );
1276 if ( sqrDist > closestSquaredDistance || sqrDist < 4 * std::numeric_limits<double>::epsilon() )
1279 closestPoint = point;
1280 closestSquaredDistance = sqrDist;
1286 rect.
scale( scaleFactor, ¢erMapCoordinates );
1326 if ( boundingBoxOfFeatureIds( ids,
layer, bbox, errorMsg ) )
1346 if ( boundingBoxOfFeatureIds( ids,
layer, bbox, errorMsg ) )
1363 int featureCount = 0;
1371 errorMsg = tr(
"Feature does not have a geometry" );
1375 errorMsg = tr(
"Feature geometry is empty" );
1377 if ( !errorMsg.isEmpty() )
1386 if ( featureCount != ids.count() )
1388 errorMsg = tr(
"Feature not found" );
1400 layer = qobject_cast<QgsVectorLayer *>( mCurrentLayer );
1419 const QColor &color1,
const QColor &color2,
1420 int flashes,
int duration )
1427 QList< QgsGeometry > geoms;
1443 if ( geometries.isEmpty() )
1459 QColor startColor = color1;
1460 if ( !startColor.isValid() )
1470 startColor.setAlpha( 255 );
1472 QColor endColor = color2;
1473 if ( !endColor.isValid() )
1475 endColor = startColor;
1476 endColor.setAlpha( 0 );
1480 QVariantAnimation *animation =
new QVariantAnimation(
this );
1481 connect( animation, &QVariantAnimation::finished,
this, [animation, rb]
1483 animation->deleteLater();
1486 connect( animation, &QPropertyAnimation::valueChanged,
this, [rb, geomType](
const QVariant & value )
1488 QColor
c = value.value<QColor>();
1497 c.setAlpha(
c.alpha() );
1503 animation->setDuration( duration * flashes );
1504 animation->setStartValue( endColor );
1505 double midStep = 0.2 / flashes;
1506 for (
int i = 0; i < flashes; ++i )
1508 double start =
static_cast< double >( i ) / flashes;
1509 animation->setKeyValueAt( start + midStep, startColor );
1510 double end =
static_cast< double >( i + 1 ) / flashes;
1512 animation->setKeyValueAt( end, endColor );
1514 animation->setEndValue( endColor );
1531 double dx = std::fabs( currentExtent.
width() / 4 );
1532 double dy = std::fabs( currentExtent.
height() / 4 );
1566 if ( ! e->isAutoRepeat() )
1568 QApplication::setOverrideCursor( Qt::ClosedHandCursor );
1574 case Qt::Key_PageUp:
1579 case Qt::Key_PageDown:
1586 mUseParallelRendering = !mUseParallelRendering;
1591 mDrawRenderingStats = !mDrawRenderingStats;
1622 QApplication::restoreOverrideCursor();
1636 QgsDebugMsgLevel(
"Ignoring key release: " + QString::number( e->key() ), 2 );
1655 void QgsMapCanvas::beginZoomRect( QPoint pos )
1657 mZoomRect.setRect( 0, 0, 0, 0 );
1658 QApplication::setOverrideCursor( mZoomCursor );
1659 mZoomDragging =
true;
1661 QColor color( Qt::blue );
1662 color.setAlpha( 63 );
1663 mZoomRubberBand->setColor( color );
1664 mZoomRect.setTopLeft( pos );
1667 void QgsMapCanvas::endZoomRect( QPoint pos )
1669 mZoomDragging =
false;
1670 mZoomRubberBand.reset(
nullptr );
1671 QApplication::restoreOverrideCursor();
1674 mZoomRect.setRight( pos.x() );
1675 mZoomRect.setBottom( pos.y() );
1677 if ( mZoomRect.width() < 5 && mZoomRect.height() < 5 )
1684 mZoomRect = mZoomRect.normalized();
1687 const QSize &zoomRectSize = mZoomRect.size();
1688 const QSize &canvasSize = mSettings.
outputSize();
1689 double sfx =
static_cast< double >( zoomRectSize.width() ) / canvasSize.width();
1690 double sfy =
static_cast< double >( zoomRectSize.height() ) / canvasSize.height();
1691 double sf = std::max( sfx, sfy );
1702 if ( e->button() == Qt::MidButton )
1713 && e->modifiers() & Qt::ShiftModifier )
1715 beginZoomRect( e->pos() );
1721 showContextMenu( me.get() );
1744 if ( e->button() == Qt::MidButton )
1749 else if ( e->button() == Qt::BackButton )
1754 else if ( e->button() == Qt::ForwardButton )
1761 if ( mZoomDragging && e->button() == Qt::LeftButton )
1763 endZoomRect( e->pos() );
1773 QgsDebugMsgLevel( QStringLiteral(
"Right click in map tool zoom or pan, last tool is %1." ).arg(
1774 mLastNonZoomMapTool ? QStringLiteral(
"not null" ) : QStringLiteral(
"null" ) ), 2 );
1776 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCurrentLayer );
1779 if ( mLastNonZoomMapTool
1784 mLastNonZoomMapTool =
nullptr;
1804 QGraphicsView::resizeEvent( e );
1805 mResizeTimer->start( 500 );
1807 double oldScale = mSettings.
scale();
1808 QSize lastSize = viewport()->size();
1811 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
1817 double scaleFactor = oldScale / mSettings.
scale();
1835 QGraphicsView::paintEvent( e );
1840 const QList<QGraphicsItem *> items = mScene->items();
1841 for ( QGraphicsItem *gi : items )
1858 QgsDebugMsgLevel(
"Wheel event delta " + QString::number( e->delta() ), 2 );
1863 if ( e->isAccepted() )
1867 if ( e->delta() == 0 )
1873 double zoomFactor = e->angleDelta().y() > 0 ? 1. / zoomInFactor() : zoomOutFactor();
1876 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( e->angleDelta().y() );
1878 if ( e->modifiers() & Qt::ControlModifier )
1881 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
1884 double signedWheelFactor = e->angleDelta().y() > 0 ? 1 / zoomFactor : zoomFactor;
1889 QgsPointXY newCenter( mousePos.
x() + ( ( oldCenter.
x() - mousePos.
x() ) * signedWheelFactor ),
1890 mousePos.
y() + ( ( oldCenter.
y() - mousePos.
y() ) * signedWheelFactor ) );
1898 mWheelZoomFactor = factor;
1920 double scaleFactor = (
zoomIn ? zoomInFactor() : zoomOutFactor() );
1940 mScaleLocked = isLocked;
1951 else if ( mZoomDragging )
1953 mZoomRect.setBottomRight( e->pos() );
1954 mZoomRubberBand->setToCanvasRectangle( mZoomRect );
1955 mZoomRubberBand->show();
1968 if ( !panOperationInProgress() )
1985 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
1995 mLastNonZoomMapTool = mMapTool;
1999 mLastNonZoomMapTool =
nullptr;
2009 connect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2017 if ( mMapTool && mMapTool == tool )
2019 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2024 setCursor( Qt::ArrowCursor );
2027 if ( mLastNonZoomMapTool && mLastNonZoomMapTool == tool )
2029 mLastNonZoomMapTool =
nullptr;
2042 QBrush bgBrush( color );
2043 setBackgroundBrush( bgBrush );
2046 palette.setColor( backgroundRole(), color );
2047 setPalette( palette );
2051 mScene->setBackgroundBrush( bgBrush );
2060 return mScene->backgroundBrush().color();
2072 bool hasSelectedFeatures =
false;
2079 hasSelectedFeatures =
true;
2084 if ( hasSelectedFeatures )
2151 if ( mTheme ==
theme )
2165 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
2183 void QgsMapCanvas::connectNotify(
const char *signal )
2186 QgsDebugMsg(
"QgsMapCanvas connected to " + QString( signal ) );
2190 void QgsMapCanvas::layerRepaintRequested(
bool deferred )
2196 void QgsMapCanvas::autoRefreshTriggered()
2202 mRefreshAfterJob =
true;
2209 void QgsMapCanvas::updateAutoRefreshTimer()
2213 int minAutoRefreshInterval = -1;
2218 minAutoRefreshInterval = minAutoRefreshInterval > 0 ? std::min(
layer->
autoRefreshInterval(), minAutoRefreshInterval ) :
layer->autoRefreshInterval();
2221 if ( minAutoRefreshInterval > 0 )
2223 mAutoRefreshTimer.setInterval( minAutoRefreshInterval );
2224 mAutoRefreshTimer.start();
2228 mAutoRefreshTimer.stop();
2232 void QgsMapCanvas::projectThemesChanged()
2234 if ( mTheme.isEmpty() )
2260 double dx = end.
x() - start.
x();
2261 double dy = end.
y() - start.
y();
2263 c.set(
c.x() - dx,
c.y() - dy );
2296 setSceneRect( -pnt.x(), -pnt.y(), viewport()->size().width(), viewport()->size().height() );
2304 bool allHandled =
true;
2307 bool handled =
false;
2310 if ( handler && handler->customUriProviderKey() == uri.providerKey )
2312 if ( handler->handleCustomUriCanvasDrop( uri,
this ) )
2340 if ( !mPreviewEffect )
2345 mPreviewEffect->setEnabled( previewEnabled );
2350 if ( !mPreviewEffect )
2355 return mPreviewEffect->isEnabled();
2360 if ( !mPreviewEffect )
2365 mPreviewEffect->
setMode( mode );
2370 if ( !mPreviewEffect )
2375 return mPreviewEffect->
mode();
2380 if ( !mSnappingUtils )
2386 return mSnappingUtils;
2391 mSnappingUtils = utils;
2396 QgsProject *project = qobject_cast< QgsProject * >( sender() );
2398 QDomNodeList nodes = doc.elementsByTagName( QStringLiteral(
"mapcanvas" ) );
2399 if ( nodes.count() )
2401 QDomNode node = nodes.item( 0 );
2404 if ( nodes.count() > 1 )
2406 for (
int i = 0; i < nodes.size(); ++i )
2408 QDomElement elementNode = nodes.at( i ).toElement();
2410 if ( elementNode.hasAttribute( QStringLiteral(
"name" ) ) && elementNode.attribute( QStringLiteral(
"name" ) ) == objectName() )
2412 node = nodes.at( i );
2420 if ( objectName() != QStringLiteral(
"theMapCanvas" ) )
2431 QDomElement elem = node.toElement();
2432 if ( elem.hasAttribute( QStringLiteral(
"theme" ) ) )
2434 if (
QgsProject::instance()->mapThemeCollection()->hasMapTheme( elem.attribute( QStringLiteral(
"theme" ) ) ) )
2436 setTheme( elem.attribute( QStringLiteral(
"theme" ) ) );
2439 setAnnotationsVisible( elem.attribute( QStringLiteral(
"annotationsVisible" ), QStringLiteral(
"1" ) ).toInt() );
2442 const QDomNodeList scopeElements = elem.elementsByTagName( QStringLiteral(
"expressionContextScope" ) );
2443 if ( scopeElements.size() > 0 )
2445 const QDomElement scopeElement = scopeElements.at( 0 ).toElement();
2451 QgsDebugMsg( QStringLiteral(
"Couldn't read mapcanvas information from project" ) );
2464 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
2467 QgsDebugMsg( QStringLiteral(
"Unable to find qgis element in project file" ) );
2470 QDomNode qgisNode = nl.item( 0 );
2472 QDomElement mapcanvasNode = doc.createElement( QStringLiteral(
"mapcanvas" ) );
2473 mapcanvasNode.setAttribute( QStringLiteral(
"name" ), objectName() );
2474 if ( !mTheme.isEmpty() )
2475 mapcanvasNode.setAttribute( QStringLiteral(
"theme" ), mTheme );
2476 mapcanvasNode.setAttribute( QStringLiteral(
"annotationsVisible" ), mAnnotationsVisible );
2477 qgisNode.appendChild( mapcanvasNode );
2479 mSettings.
writeXml( mapcanvasNode, doc );
2482 QDomElement scopeElement = doc.createElement( QStringLiteral(
"expressionContextScope" ) );
2484 tmpScope.
removeVariable( QStringLiteral(
"atlas_featurenumber" ) );
2490 mapcanvasNode.appendChild( scopeElement );
2497 if ( mScaleLocked && !ignoreScaleLock )
2534 bool allHandled =
true;
2537 bool handled =
false;
2540 if ( handler->canHandleCustomUriCanvasDrop( uri,
this ) )
2560 void QgsMapCanvas::mapToolDestroyed()
2568 if ( !QTouchDevice::devices().empty() )
2570 if ( e->type() == QEvent::Gesture )
2572 if ( QTapAndHoldGesture *tapAndHoldGesture = qobject_cast< QTapAndHoldGesture * >(
static_cast<QGestureEvent *
>( e )->gesture( Qt::TapAndHoldGesture ) ) )
2574 QPointF pos = tapAndHoldGesture->position();
2575 pos = mapFromGlobal( QPoint( pos.x(), pos.y() ) );
2583 return mMapTool->
gestureEvent(
static_cast<QGestureEvent *
>( e ) );
2589 return QGraphicsView::event( e );
2615 while ( mRefreshScheduled || mJob )
2617 QgsApplication::processEvents();
2633 QList<QgsMapCanvasAnnotationItem *> annotationItemList;
2634 const QList<QGraphicsItem *> items = mScene->items();
2635 for ( QGraphicsItem *gi : items )
2640 annotationItemList.push_back( aItem );
2644 return annotationItemList;
2649 mAnnotationsVisible = show;
2653 item->setVisible( show );
2667 void QgsMapCanvas::startPreviewJobs()
2676 schedulePreviewJob( 0 );
2679 void QgsMapCanvas::startPreviewJob(
int number )
2692 double dx = ( i - 1 ) * mapRect.
width();
2693 double dy = ( 1 - j ) * mapRect.
height();
2706 const QList<QgsMapLayer *>
layers = jobSettings.
layers();
2707 QList< QgsMapLayer * > previewLayers;
2716 QgsDebugMsgLevel( QStringLiteral(
"Layer %1 not rendered because it does not match the renderInPreview criterion %2" ).arg(
layer->
id() ).arg( mLastLayerRenderTime.value(
layer->
id() ) ), 3 );
2720 previewLayers <<
layer;
2725 job->setProperty(
"number", number );
2726 mPreviewJobs.append( job );
2731 void QgsMapCanvas::stopPreviewJobs()
2733 mPreviewTimer.stop();
2734 const auto previewJobs = mPreviewJobs;
2735 for (
auto previewJob : previewJobs )
2741 previewJob->cancelWithoutBlocking();
2744 mPreviewJobs.clear();
2747 void QgsMapCanvas::schedulePreviewJob(
int number )
2749 mPreviewTimer.setSingleShot(
true );
2750 mPreviewTimer.setInterval( PREVIEW_JOB_DELAY_MS );
2751 disconnect( mPreviewTimerConnection );
2752 mPreviewTimerConnection = connect( &mPreviewTimer, &QTimer::timeout,
this, [ = ]()
2754 startPreviewJob( number );
2756 mPreviewTimer.start();
2759 bool QgsMapCanvas::panOperationInProgress()
2764 if (
QgsMapToolPan *panTool = qobject_cast< QgsMapToolPan *>( mMapTool ) )
2766 if ( panTool->isDragging() )
2773 int QgsMapCanvas::nextZoomLevel(
const QList<double> &resolutions,
bool zoomIn )
const
2775 int resolutionLevel = -1;
2778 for (
int i = 0, n = resolutions.size(); i < n; ++i )
2780 if (
qgsDoubleNear( resolutions[i], currentResolution, 0.0001 ) )
2782 resolutionLevel =
zoomIn ? ( i - 1 ) : ( i + 1 );
2785 else if ( currentResolution <= resolutions[i] )
2787 resolutionLevel =
zoomIn ? ( i - 1 ) : i;
2791 return ( resolutionLevel < 0 || resolutionLevel >= resolutions.size() ) ? -1 : resolutionLevel;
2794 double QgsMapCanvas::zoomInFactor()
const
2796 if ( !mZoomResolutions.isEmpty() )
2798 int zoomLevel = nextZoomLevel( mZoomResolutions,
true );
2799 if ( zoomLevel != -1 )
2804 return 1 / mWheelZoomFactor;
2807 double QgsMapCanvas::zoomOutFactor()
const
2809 if ( !mZoomResolutions.isEmpty() )
2811 int zoomLevel = nextZoomLevel( mZoomResolutions,
false );
2812 if ( zoomLevel != -1 )
2817 return mWheelZoomFactor;
QPoint rubberStartPoint
Beginning point of a rubber band.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
void renderStarting()
Emitted when the canvas is about to be rendered.
void mouseDoubleClickEvent(QMouseEvent *e) override
@ MaximumAngle
Maximum angle between generating radii (lines from arc center to output vertices)
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QgsCoordinateReferenceSystem crs
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
void renderErrorOccurred(const QString &error, QgsMapLayer *layer)
Emitted whenever an error is encountered during a map render operation.
void panToSelected(QgsVectorLayer *layer=nullptr)
Pan to the selected features of current (vector) layer keeping same extent.
void currentLayerChanged(QgsMapLayer *layer)
Emitted when the current layer is changed.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
sets destination coordinate reference system
void dropEvent(QDropEvent *event) override
void waitWhileRendering()
Blocks until the rendering job has finished.
void zoomToPreviousExtent()
Zoom to the previous extent (view)
virtual QgsTemporalProperty::Flags flags() const
Returns flags associated to the temporal property.
bool hasAutoRefreshEnabled() const
Returns true if auto refresh is enabled for the layer.
virtual bool usedCachedLabels() const =0
Returns true if the render job was able to use a cached labeling solution.
QgsRectangle extent() const
Returns the current zoom extent of the map canvas.
QPoint mouseLastXY
Last seen point of the mouse.
void moveCanvasContents(bool reset=false)
called when panning is in action, reset indicates end of panning
void mapThemeRenamed(const QString &name, const QString &newName)
Emitted when a map theme within the collection is renamed.
QgsPointXY mapToLayerCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from output CRS to layer's CRS
void setTheme(const QString &theme)
Sets a map theme to show in the canvas.
const QgsProjectViewSettings * viewSettings() const
Returns the project's view settings, which contains settings and properties relating to how a QgsProj...
void mapToolSet(QgsMapTool *newTool, QgsMapTool *oldTool)
Emit map tool changed with the old tool.
const QgsMapSettings & mapSettings() const
Returns map settings with which this job was started.
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
void refresh()
Repaints the canvas map.
void setFlag(Flag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected)
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.
void setWheelFactor(double factor)
Sets wheel zoom factor (should be greater than 1)
bool isDrawing()
Find out whether rendering is in progress.
double mapUnitsPerPixel() const
Returns current map units per pixel.
void readXml(QDomNode &node)
@ ICON_CIRCLE
A circle is used to highlight points (â—‹)
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void waitForFinished() override
Block until the job has finished.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context.
void destinationCrsChanged()
Emitted when map CRS has changed.
QSize outputSize() const
Returns the size of the resulting map image.
void zoomScale(double scale, bool ignoreScaleLock=false)
Zooms the canvas to a specific scale.
void xyCoordinates(const QgsPointXY &p)
Emits current mouse position.
void setRotation(double rotation)
Sets the rotation of the resulting map image, in degrees clockwise.
QgsMapTool * mapTool()
Returns the currently active tool.
void zoomByFactor(double scaleFactor, const QgsPointXY *center=nullptr, bool ignoreScaleLock=false)
Zoom with the factor supplied.
virtual bool isActive() const =0
Tell whether the rendering job is currently running in background.
void zoomOut()
Zoom out with fixed factor.
QString userFriendlyIdentifier(IdentifierType type=MediumString) const
Returns a user friendly identifier for the CRS.
void zoomLastStatusChanged(bool)
Emitted when zoom last status changed.
QPoint mouseLastXY()
returns last position of mouse cursor
void setXMinimum(double x)
Set the minimum x value.
void mouseMoveEvent(QMouseEvent *e) override
#define QgsDebugMsgLevel(str, level)
constexpr double CANVAS_MAGNIFICATION_MIN
Minimum magnification level allowed in map canvases.
@ WKT_PREFERRED
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
void redrawAllLayers()
Clears all cached images and redraws all layers.
double sqrDist(double x, double y) const
Returns the squared distance between this point a specified x, y coordinate.
float devicePixelRatio() const
Returns device pixel ratio Common values are 1 for normal-dpi displays and 2 for high-dpi "retina" di...
void readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads scope variables from an XML element.
virtual QImage renderedImage()=0
Gets a preview/resulting image.
const QgsCoordinateReferenceSystem & crs
bool mouseButtonDown
Flag to indicate status of mouse button.
static QCursor getThemeCursor(Cursor cursor)
Helper to get a theme cursor.
void setIsTemporal(bool enabled)
Sets whether the temporal range is enabled (i.e.
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.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
void mouseReleaseEvent(QMouseEvent *e) override
void mapThemeChanged(const QString &theme)
Emitted when a map theme changes definition.
void temporalRangeChanged()
Emitted when the map canvas temporal range changes.
void clear()
Invalidates the cache contents, clearing all cached images.
bool hasValidSettings() const
Check whether the map settings are valid and can be used for rendering.
void panActionEnd(QPoint releasePoint)
Ends pan action and redraws the canvas.
void setMagnificationFactor(double factor, const QgsPointXY *center=nullptr)
Sets the factor of magnification to apply to the map canvas.
QgsRectangle fullExtent() const
returns current extent of layer set
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
void writeXml(QDomNode &node, QDomDocument &doc)
QgsPointXY center() const
Gets map center, in geographical coordinates.
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes scope variables to an XML element.
QgsCoordinateTransformContext transformContext
const QgsDateTimeRange & temporalRange() const
Returns the datetime range for the object.
QgsRectangle fullExtent() const
Returns the combined extent for all layers on the map canvas.
double mapUnitsPerPixel() const
Returns the distance in geographical coordinates that equals to one pixel in the map.
void setRotation(double degrees)
Set the rotation of the map canvas in clockwise degrees.
static QgsExpressionContextScope * mapSettingsScope(const QgsMapSettings &mapSettings)
Creates a new scope which contains variables and functions relating to a QgsMapSettings object.
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsRectangle layerExtentToOutputExtent(const QgsMapLayer *layer, QgsRectangle extent) const
transform bounding box from layer's CRS to output CRS
void setStrokeColor(const QColor &color)
Sets the stroke color for the rubberband.
double scale() const
Returns the last reported scale of the canvas.
void rotationChanged(double)
Emitted when the rotation of the map changes.
void readProject(const QDomDocument &)
Emitted when a project is being read.
void zoomWithCenter(int x, int y, bool zoomIn)
Zooms in/out with a given center.
double magnificationFactor() const
Returns the magnification factor.
void setFillColor(const QColor &color)
Sets the fill color for the rubberband.
QMap< QString, QString > layerStyleOverrides() const
Gets map of map layer style overrides (key: layer ID, value: style name) where a different style shou...
void writeProject(QDomDocument &)
called to write map canvas settings to project
void selectionChangedSlot()
Receives signal about selection change, and pass it on with layer info.
void panAction(QMouseEvent *event)
Called when mouse is moving and pan is activated.
virtual void reload()
Synchronises with changes in the datasource.
void clearCache()
Make sure to remove any rendered images from cache (does nothing if cache is not enabled)
@ RenderPartialOutput
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
bool panSelectorDown
Flag to indicate the pan selector key is held down by user.
QgsUnitTypes::DistanceUnit mapUnits() const
Convenience function for returning the current canvas map units.
SegmentationToleranceType
Segmentation tolerance as maximum angle or maximum difference between approximation and circle.
QList< QgsMimeDataUtils::Uri > UriList
void dragEnterEvent(QDragEnterEvent *e) override
DistanceUnit
Units of distance.
void paintEvent(QPaintEvent *e) override
Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
QColor secondaryStrokeColor
void freeze(bool frozen=true)
Freeze/thaw the map canvas.
QList< QgsMapLayer * > layers() const
Returns the list of layers shown within the map canvas.
void wheelEvent(QWheelEvent *e) override
QgsMapCanvas(QWidget *parent=nullptr)
Constructor.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
void start() override
Start the rendering job and immediately return.
void setMapSettingsFlags(QgsMapSettings::Flags flags)
Resets the flags for the canvas' map settings.
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
constexpr double CANVAS_MAGNIFICATION_MAX
Maximum magnification level allowed in map canvases.
QgsSnappingUtils * snappingUtils() const
Returns snapping utility class that is associated with map canvas.
void setPreviewJobsEnabled(bool enabled)
Sets whether canvas map preview jobs (low priority render jobs which render portions of the view just...
bool allowInteraction(QgsMapCanvasInteractionBlocker::Interaction interaction) const
Returns true if the specified interaction is currently permitted on the canvas.
void scaleChanged(double)
Emitted when the scale of the map changes.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
void writeProject(QDomDocument &)
Emitted when the project is being written.
@ DrawLabeling
Enable drawing of labels on top of the map.
bool isParallelRenderingEnabled() const
Check whether the layers are rendered in parallel or sequentially.
int renderingTime() const
Returns the total time it took to finish the job (in milliseconds).
const QgsLabelingResults * labelingResults() const
Gets access to the labeling results (may be nullptr)
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
void setCurrentLayer(QgsMapLayer *layer)
Errors errors() const
List of errors that happened during the rendering job - available when the rendering has been finishe...
virtual void updatePosition()
called on changed extent or resize event to update position of the item
double rotation() const
Gets the current map canvas rotation in clockwise degrees.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
void zoomIn()
Zoom in with fixed factor.
void readProject(const QDomDocument &)
called to read map canvas settings from project
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
void enableAntiAliasing(bool flag)
used to determine if anti-aliasing is enabled or not
void setBackgroundColor(const QColor &color)
Sets the background color of the map.
void setTemporalController(QgsTemporalController *controller)
Sets the temporal controller, tQgsMapCanvasInteractionBlockerhis controller will be used to update th...
QgsReferencedRectangle defaultViewExtent() const
Returns the default view extent, which should be used as the initial map extent when this project is ...
void setPreviewMode(QgsPreviewEffect::PreviewMode mode)
Sets a preview mode for the map canvas.
QHash< QgsMapLayer *, int > perLayerRenderingTime() const
Returns the render time (in ms) per layer.
virtual QgsDataProvider * dataProvider()
Returns the layer's data provider, it may be nullptr.
int layerCount() const
Returns number of layers on the map.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
virtual void waitForFinished()=0
Block until the job has finished.
QMap< QString, QString > layerStyleOverrides() const
Returns the stored overrides of styles for layers.
bool isActive() const
Returns true if the temporal property is active.
@ DistanceDegrees
Degrees, for planar geographic CRS distance measurements.
double bearing(const QgsPointXY &p1, const QgsPointXY &p2) const
Computes the bearing (in radians) between two points.
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
QColor canvasColor() const
Read property of QColor bgColor.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
void zoomToSelected(QgsVectorLayer *layer=nullptr)
Zoom to the extent of the selected features of provided (vector) layer.
Interaction
Available interactions to block.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
void layersChanged()
Emitted when a new set of layers has been received.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
QgsMapLayer * layer(int index)
Returns the map layer at position index in the layer stack.
void setCache(QgsMapRendererCache *cache)
Assign a cache to be used for reading and storing rendered images of individual layers.
QgsUnitTypes::DistanceUnit mapUnits() const
Gets units of map's geographical coordinates - used for scale calculation.
void setMagnificationFactor(double factor, const QgsPointXY *center=nullptr)
Set the magnification factor.
void keyReleaseEvent(QKeyEvent *e) override
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
void extentsChanged()
Emitted when the extents of the map change.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
void mapThemesChanged()
Emitted when map themes within the collection are changed.
void updateCanvasItemPositions()
called on resize or changed extent to notify canvas items to change their rectangle
@ Antialiasing
Enable anti-aliasing for map rendering.
QgsUnitTypes::DistanceUnit lengthUnits() const
Returns the units of distance for length calculations made by this object.
static QgsImageCache * imageCache()
Returns the application's image cache, used for caching resampled versions of raster images.
virtual QgsMapLayerTemporalProperties * temporalProperties()
Returns the layer's temporal properties.
Stores settings related to the context in which a preview job runs.
void setTemporalRange(const QgsDateTimeRange &range)
Set datetime range for the map canvas.
std::unique_ptr< CanvasProperties > mCanvasProperties
Handle pattern for implementation object.
void setSelectionColor(const QColor &color)
Sets color that is used for drawing of selected vector features.
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
void updateScale()
Emits signal scaleChanged to update scale in main window.
void setXMaximum(double x)
Set the maximum x value.
static void warning(const QString &msg)
Goes to qWarning.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
sets destination coordinate reference system
void setCanvasColor(const QColor &_newVal)
Write property of QColor bgColor.
void setCenter(const QgsPointXY ¢er)
Set the center of the map canvas, in geographical coordinates.
void setFlags(QgsMapSettings::Flags flags)
Sets combination of flags that will be used for rendering.
void resizeEvent(QResizeEvent *e) override
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns global labeling engine settings from the internal map settings.
void enableMapTileRendering(bool flag)
sets map tile rendering flag
void zoomToFullExtent()
Zoom to the full extent of all layers.
QColor selectionColor() const
Returns color for selected features.
double scale() const
Returns the calculated map scale.
void layerStyleOverridesChanged()
Emitted when the configuration of overridden layer styles changes.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
QgsMapThemeCollection mapThemeCollection
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
double maxRenderingTimeMs
Default maximum allowable render time, in ms.
void zoomToNextExtent()
Zoom to the next extent (view)
bool setReferencedExtent(const QgsReferencedRectangle &extent) SIP_THROW(QgsCsException)
Sets the canvas to the specified extent.
virtual void start()=0
Start the rendering job and immediately return.
void refreshAllLayers()
Reload all layers (including refreshing layer properties from their data sources),...
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
void setExtent(const QgsRectangle &r, bool magnified=false)
Sets the extent of the map canvas to the specified rectangle.
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
void transformContextChanged()
Emitted when the project transformContext() is changed.
void setMapTool(QgsMapTool *mapTool, bool clean=false)
Sets the map tool currently being used on the canvas.
QgsPreviewEffect::PreviewMode previewMode() const
Returns the current preview mode for the map canvas.
const QgsMapToPixel * getCoordinateTransform()
Gets the current coordinate transform.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
void setParallelRenderingEnabled(bool enabled)
Set whether the layers are rendered in parallel or sequentially.
void panToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids, bool alwaysRecenter=true)
Centers canvas extent to feature ids.
virtual bool isEmpty() const
Returns true if the geometry is empty.
QSet< QgsFeatureId > QgsFeatureIds
void keyPressEvent(QKeyEvent *e) override
void zoomToFeatureExtent(QgsRectangle &rect)
Zooms to feature extent.
void saveAsImage(const QString &fileName, QPixmap *QPixmap=nullptr, const QString &="PNG")
Save the contents of the map canvas to disk as an image.
virtual bool renderInPreview(const QgsDataProvider::PreviewContext &context)
Returns whether the layer must be rendered in preview jobs.
QColor selectionColor() const
Gets color that is used for drawing of selected vector features.
static QString worldFileContent(const QgsMapSettings &mapSettings)
Creates the content of a world file.
void setRenderFlag(bool flag)
Sets whether a user has disabled canvas renders via the GUI.
int mapUpdateInterval() const
Find out how often map preview should be updated while it is being rendered (in milliseconds)
double yMaximum() const
Returns the y maximum value (top side of rectangle).
@ RenderPreviewJob
Render is a 'canvas preview' render, and shortcuts should be taken to ensure fast rendering.
Single scope for storing variables and functions for use within a QgsExpressionContext....
static QgsSvgCache * svgCache()
Returns the application's SVG cache, used for caching SVG images and handling parameter replacement w...
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets the global configuration of the labeling engine.
void setLayers(const QList< QgsMapLayer * > &layers)
Set list of layers for map rendering.
void setScaleLocked(bool isLocked)
Lock the scale, so zooming can be performed using magnication.
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.
QgsCoordinateReferenceSystem destinationCrs() const
returns CRS of destination coordinate reference system
@ ShortString
A heavily abbreviated string, for use when a compact representation is required.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
void removeInteractionBlocker(QgsMapCanvasInteractionBlocker *blocker)
Removes an interaction blocker from the canvas.
void setMapUpdateInterval(int timeMilliseconds)
Set how often map preview should be updated while it is being rendered (in milliseconds)
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
void keyReleased(QKeyEvent *e)
Emit key release event.
const QgsDateTimeRange & temporalRange() const
Returns map canvas datetime range.
void clearExtentHistory()
@ UseRenderingOptimization
Enable vector simplification and other rendering optimizations.
void updateTemporalRange(const QgsDateTimeRange &range)
Signals that a temporal range has changed and needs to be updated in all connected objects.
bool event(QEvent *e) override
QgsUnitTypes::DistanceUnit mapUnits
void setWidth(int width)
Sets the width of the line.
void setAnnotationsVisible(bool visible)
Sets whether annotations are visible in the canvas.
QgsPointXY center() const
Returns the center point of the rectangle.
void canvasColorChanged()
Emitted when canvas background color changes.
static UriList decodeUriList(const QMimeData *data)
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
bool testFlag(Flag flag) const
Check whether a particular flag is enabled.
void tapAndHoldGestureOccurred(const QgsPointXY &mapPoint, QTapAndHoldGesture *gesture)
Emitted whenever a tap and hold gesture occurs at the specified map point.
void setCustomDropHandlers(const QVector< QPointer< QgsCustomDropHandler >> &handlers)
Sets a list of custom drop handlers to use when drop events occur on the canvas.
bool nextFeature(QgsFeature &f)
void themeChanged(const QString &theme)
Emitted when the canvas has been assigned a different map theme.
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
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Set map of map layer style overrides (key: layer ID, value: style name) where a different style shoul...
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isCachingEnabled() const
Check whether images of rendered layers are curerently being cached.
void selectionChanged(QgsVectorLayer *layer)
Emitted when selection in any layer gets changed.
@ DrawEditingInfo
Enable drawing of vertex markers for layers in editing mode.
QgsFeatureRequest & setLimit(long limit)
Set the maximum number of features to request.
bool isFrozen() const
Returns true if canvas is frozen.
void addGeometry(const QgsGeometry &geometry, QgsVectorLayer *layer)
Adds the geometry of an existing feature to a rubberband This is useful for multi feature highlightin...
void magnificationChanged(double)
Emitted when the scale of the map changes.
double height() const
Returns the height of the rectangle.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
virtual void cancelWithoutBlocking()=0
Triggers cancellation of the rendering job without blocking.
bool previewModeEnabled() const
Returns whether a preview mode is enabled for the map canvas.
void setPreviewModeEnabled(bool previewEnabled)
Enables a preview mode for the map canvas.
void panDistanceBearingChanged(double distance, QgsUnitTypes::DistanceUnit unit, double bearing)
Emitted whenever the distance or bearing of an in-progress panning operation is changed.
QgsExpressionContextScope * defaultExpressionContextScope()
Creates a new scope which contains default variables and functions relating to the map canvas.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
void setIcon(IconType icon)
Sets the icon type to highlight point geometries.
void keyPressed(QKeyEvent *e)
Emit key press event.
void unsetMapTool(QgsMapTool *mapTool)
Unset the current map tool or last non zoom tool.
void mousePressEvent(QMouseEvent *e) override
static QgsExpressionContextScope * atlasScope(const QgsLayoutAtlas *atlas)
Creates a new scope which contains variables and functions relating to a QgsLayoutAtlas.
void renderComplete(QPainter *)
Emitted when the canvas has rendered.
QList< QgsMapLayer * > layers() const
Gets list of layers for map rendering The layers are stored in the reverse order of how they are rend...
void setTemporalRange(const QgsDateTimeRange &range)
Sets the temporal range for the object.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
void setMode(PreviewMode mode)
Sets the mode for the preview effect, which controls how the effect modifies a widgets appearance.
void messageEmitted(const QString &title, const QString &message, Qgis::MessageLevel=Qgis::Info)
emit a message (usually to be displayed in a message bar)
double magnificationFactor() const
Returns the magnification factor.
virtual QgsLabelingResults * takeLabelingResults()=0
Gets pointer to internal labeling engine (in order to get access to the results).
QgsMapLayer * currentLayer()
returns current layer (set by legend widget)
void setSnappingUtils(QgsSnappingUtils *utils)
Assign an instance of snapping utils to the map canvas.
bool hasMapTheme(const QString &name) const
Returns whether a map theme with a matching name exists.
double lastRenderingTimeMs
Previous rendering time for the layer, in ms.
void zoomToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids)
Set canvas extent to the bounding box of a set of features.
void remoteImageFetched(const QString &url)
Emitted when the cache has finished retrieving an image file from a remote url.
void zoomNextStatusChanged(bool)
Emitted when zoom next status changed.
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
void setMinimal()
Set a rectangle so that min corner is at max and max corner is at min.
T enumValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on an enum.
virtual bool isSpatial() const
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the list of layers that should be shown in the canvas.
void setOutputSize(QSize size)
Sets the size of the resulting map image.
void installInteractionBlocker(QgsMapCanvasInteractionBlocker *blocker)
Installs an interaction blocker onto the canvas, which may prevent certain map canvas interactions fr...
void panActionStart(QPoint releasePoint)
Starts a pan action.
double mapUnitsPerPixel() const
Returns the mapUnitsPerPixel (map units per pixel) for the canvas.
void setPathResolver(const QgsPathResolver &resolver)
Sets the path resolver for conversion between relative and absolute paths during rendering operations...
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes takes output image size into accou...
void invalidateCacheForLayer(QgsMapLayer *layer)
Invalidates cached images which relate to the specified map layer.
CanvasProperties()=default
Constructor for CanvasProperties.
QList< QgsMapCanvasAnnotationItem * > annotationItems() const
Returns a list of all annotation items in the canvas.
QgsPointXY layerToMapCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from layer's CRS to output CRS
void setExtent(const QgsRectangle &rect, bool magnified=true)
Set coordinates of the rectangle which should be rendered.
void setSecondaryStrokeColor(const QColor &color)
Sets a secondary stroke color for the rubberband which will be drawn under the main stroke color.
bool isEmpty() const
Returns true if the rectangle is empty.
const QgsMapToPixel & mapToPixel() const
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
@ FlagDontInvalidateCachedRendersWhenRangeChanges
Any cached rendering will not be invalidated when temporal range context is modified.
double width() const
Returns the width of the rectangle.
void setYMinimum(double y)
Set the minimum y value.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the stored overrides of styles for rendering layers.
void autoRefreshIntervalChanged(int interval)
Emitted when the auto refresh interval changes.
void setYMaximum(double y)
Set the maximum y value.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
static bool isUriList(const QMimeData *data)
PreviewMode mode() const
Returns the mode used for the preview effect.
void setCachingEnabled(bool enabled)
Set whether to cache images of rendered layers.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets global labeling engine settings in the internal map settings.
const QgsTemporalController * temporalController() const
Gets access to the temporal controller that will be used to update the canvas temporal range.
void finished()
emitted when asynchronous rendering is finished (or canceled).
void mapCanvasRefreshed()
Emitted when canvas finished a refresh request.
void setSelectionColor(const QColor &color)
Set color of selected vector features.
void layerStateChange()
This slot is connected to the visibility change of one or more layers.
void stopRendering()
stop rendering (if there is any right now)
void remoteSvgFetched(const QString &url)
Emitted when the cache has finished retrieving an SVG file from a remote url.
bool removeVariable(const QString &name)
Removes a variable from the context scope, if found.