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> 110 : QGraphicsView( parent )
112 , mExpressionContextScope( tr(
"Map Canvas" ) )
114 mScene =
new QGraphicsScene();
116 setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
117 setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
118 setMouseTracking(
true );
119 setFocusPolicy( Qt::StrongFocus );
121 mResizeTimer =
new QTimer(
this );
122 mResizeTimer->setSingleShot(
true );
125 mRefreshTimer =
new QTimer(
this );
126 mRefreshTimer->setSingleShot(
true );
127 connect( mRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::refreshMap );
130 mMap =
new QgsMapCanvasMap(
this );
168 double segmentationTolerance = settings.
value( QStringLiteral(
"qgis/segmentationTolerance" ),
"0.01745" ).toDouble();
173 mWheelZoomFactor = settings.
value( QStringLiteral(
"qgis/zoom_factor" ), 2 ).toDouble();
175 QSize s = viewport()->size();
178 setSceneRect( 0, 0, s.width(), s.height() );
179 mScene->setSceneRect( QRectF( 0, 0, s.width(), s.height() ) );
184 if ( window()->windowHandle() )
186 connect( window()->windowHandle(), &QWindow::screenChanged,
this, [ = ]( QScreen * ) {mSettings.
setDevicePixelRatio( devicePixelRatio() );} );
187 connect( window()->windowHandle()->screen(), &QScreen::physicalDotsPerInchChanged,
this, [ = ]( qreal ) {mSettings.
setDevicePixelRatio( devicePixelRatio() );} );
190 connect( &mMapUpdateTimer, &QTimer::timeout,
this, &QgsMapCanvas::mapUpdateTimeout );
191 mMapUpdateTimer.setInterval( 250 );
196 grabGesture( Qt::PinchGesture );
197 grabGesture( Qt::TapAndHoldGesture );
198 viewport()->setAttribute( Qt::WA_AcceptTouchEvents );
202 viewport()->setGraphicsEffect( mPreviewEffect );
206 connect( &mAutoRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::autoRefreshTriggered );
210 setInteractive(
false );
228 mLastNonZoomMapTool =
nullptr;
238 QList< QgsMapRendererQImageJob * >::const_iterator previewJob = mPreviewJobs.constBegin();
239 for ( ; previewJob != mPreviewJobs.constEnd(); ++previewJob )
251 qDeleteAll( mScene->items() );
253 mScene->deleteLater();
256 delete mLabelingResults;
264 factor = qBound( magnifierMin, factor, magnifierMax );
293 if ( index >= 0 && index < layers.size() )
294 return layers[index];
301 if ( mCurrentLayer == layer )
304 mCurrentLayer =
layer;
315 return nullptr != mJob;
328 if ( !mTheme.isEmpty() )
331 setLayersPrivate( layers );
334 void QgsMapCanvas::setLayersPrivate(
const QList<QgsMapLayer *> &
layers )
336 QList<QgsMapLayer *> oldLayers = mSettings.
layers();
339 if ( layers == oldLayers )
342 const auto constOldLayers = oldLayers;
355 const auto constLayers =
layers;
371 updateAutoRefreshTimer();
393 rect = transform.transformBoundingBox( mSettings.
visibleExtent() );
398 QgsDebugMsg( QStringLiteral(
"Transform error caught: %1" ).arg( e.
what() ) );
410 QgsDebugMsgLevel( QStringLiteral(
"refreshing after destination CRS changed" ), 2 );
425 return mLabelingResults;
452 return nullptr != mCache;
463 mUseParallelRendering = enabled;
468 return mUseParallelRendering;
473 mMapUpdateTimer.setInterval( timeMilliseconds );
478 return mMapUpdateTimer.interval();
484 return mCurrentLayer;
499 QgsDebugMsgLevel( QStringLiteral(
"CANVAS refresh - invalid settings -> nothing to do" ), 2 );
503 if ( !mRenderFlag || mFrozen )
509 if ( mRefreshScheduled )
511 QgsDebugMsgLevel( QStringLiteral(
"CANVAS refresh already scheduled" ), 2 );
515 mRefreshScheduled =
true;
520 mRefreshTimer->start( 1 );
523 void QgsMapCanvas::refreshMap()
525 Q_ASSERT( mRefreshScheduled );
544 if ( !mTheme.isEmpty() )
557 mJobCanceled =
false;
558 if ( mUseParallelRendering )
573 mRefreshScheduled =
false;
575 mMapUpdateTimer.start();
580 void QgsMapCanvas::mapThemeChanged(
const QString &
theme )
582 if ( theme == mTheme )
587 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
600 void QgsMapCanvas::rendererJobFinished()
602 QgsDebugMsgLevel( QStringLiteral(
"CANVAS finish! %1" ).arg( !mJobCanceled ), 2 );
604 mMapUpdateTimer.stop();
607 const auto constErrors = mJob->
errors();
621 delete mLabelingResults;
632 if ( settings.
value( QStringLiteral(
"Map/logCanvasRefreshEvent" ),
false ).toBool() )
634 QString logMsg = tr(
"Canvas refresh: %1 ms" ).arg( mJob->
renderingTime() );
638 if ( mDrawRenderingStats )
640 int w = img.width(), h = img.height();
641 QFont fnt = p.font();
644 int lh = p.fontMetrics().height() * 2;
645 QRect r( 0, h - lh, w, lh );
646 p.setPen( Qt::NoPen );
647 p.setBrush( QColor( 0, 0, 0, 110 ) );
649 p.setPen( Qt::white );
650 QString msg = QStringLiteral(
"%1 :: %2 ms" ).arg( mUseParallelRendering ? QStringLiteral(
"PARALLEL" ) : QStringLiteral(
"SEQUENTIAL" ) ).arg( mJob->
renderingTime() );
651 p.drawText( r, msg, QTextOption( Qt::AlignCenter ) );
656 mMap->setContent( img, imageRect( img, mSettings ) );
658 mLastLayerRenderTime.clear();
660 for (
auto it = times.constBegin(); it != times.constEnd(); ++it )
662 mLastLayerRenderTime.insert( it.key()->id(), it.value() );
664 if ( mUsePreviewJobs )
676 void QgsMapCanvas::previewJobFinished()
684 mPreviewJobs.removeAll( job );
686 int number = job->property(
"number" ).toInt();
689 startPreviewJob( number + 1 );
706 QgsLogger::warning( QStringLiteral(
"The renderer map has a wrong device pixel ratio" ) );
710 QgsRectangle rect( topLeft.
x(), topLeft.
y(), topLeft.
x() + img.width()*res, topLeft.
y() - img.height()*res );
716 return mUsePreviewJobs;
721 mUsePreviewJobs = enabled;
726 mDropHandlers = handlers;
729 void QgsMapCanvas::mapUpdateTimeout()
734 mMap->setContent( img, imageRect( img, mSettings ) );
763 image = theQPixmap->toImage();
764 painter.begin( &image );
774 image = mMap->contentImage().copy();
775 painter.begin( &image );
779 QStyleOptionGraphicsItem option;
780 option.initFrom(
this );
781 QGraphicsItem *item =
nullptr;
782 QListIterator<QGraphicsItem *> i( items() );
784 while ( i.hasPrevious() )
788 if ( !( item && dynamic_cast< QgsMapCanvasAnnotationItem * >( item ) ) )
795 QPointF itemScenePos = item->scenePos();
796 painter.translate( itemScenePos.x(), itemScenePos.y() );
798 item->paint( &painter, &option );
804 image.save( fileName, format.toLocal8Bit().data() );
806 QFileInfo myInfo = QFileInfo( fileName );
809 QString outputSuffix = myInfo.suffix();
810 QString myWorldFileName = myInfo.absolutePath() +
'/' + myInfo.baseName() +
'.' 811 + outputSuffix.at( 0 ) + outputSuffix.at( myInfo.suffix().size() - 1 ) +
'w';
812 QFile myWorldFile( myWorldFileName );
813 if ( !myWorldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
817 QTextStream myStream( &myWorldFile );
838 if ( ( r == current ) && magnified )
851 QgsDebugMsgLevel( QStringLiteral(
"Empty extent - keeping old scale with new center!" ), 2 );
860 if ( mLastExtent.size() > 20 )
861 mLastExtent.removeAt( 0 );
864 for (
int i = mLastExtent.size() - 1; i > mLastExtentIndex; i-- )
866 mLastExtent.removeAt( i );
869 mLastExtent.append(
extent() );
872 if ( mLastExtent.size() > 20 )
874 mLastExtent.removeAt( 0 );
878 mLastExtentIndex = mLastExtent.size() - 1;
891 canvasExtent = ct.transform( extent );
893 if ( canvasExtent.isEmpty() )
906 const double x = center.
x();
907 const double y = center.
y();
912 if ( ! rect.isEmpty() )
963 extent.
scale( 1.05 );
973 if ( mLastExtentIndex > 0 )
976 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
989 if ( mLastExtentIndex < mLastExtent.size() - 1 )
992 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
1004 mLastExtent.clear();
1005 mLastExtent.append(
extent() ) ;
1006 mLastExtentIndex = mLastExtent.size() - 1;
1036 int scaleFactor = 5;
1044 double closestSquaredDistance = pow( extentRect.
width(), 2.0 ) + pow( extentRect.
height(), 2.0 );
1045 bool pointFound =
false;
1049 double sqrDist = point.
sqrDist( centerLayerCoordinates );
1050 if ( sqrDist > closestSquaredDistance || sqrDist < 4 * std::numeric_limits<double>::epsilon() )
1053 closestPoint = point;
1054 closestSquaredDistance = sqrDist;
1060 rect.
scale( scaleFactor, ¢erMapCoordinates );
1076 rect.
scale( 1.0, &c );
1100 if ( boundingBoxOfFeatureIds( ids, layer, bbox, errorMsg ) )
1120 if ( boundingBoxOfFeatureIds( ids, layer, bbox, errorMsg ) )
1137 int featureCount = 0;
1145 errorMsg = tr(
"Feature does not have a geometry" );
1149 errorMsg = tr(
"Feature geometry is empty" );
1151 if ( !errorMsg.isEmpty() )
1160 if ( featureCount != ids.count() )
1162 errorMsg = tr(
"Feature not found" );
1193 const QColor &color1,
const QColor &color2,
1194 int flashes,
int duration )
1201 QList< QgsGeometry > geoms;
1217 if ( geometries.isEmpty() )
1223 rb->addGeometry( geom, crs );
1228 rb->setSecondaryStrokeColor( QColor( 255, 255, 255 ) );
1233 QColor startColor = color1;
1234 if ( !startColor.isValid() )
1238 startColor = rb->fillColor();
1242 startColor = rb->strokeColor();
1244 startColor.setAlpha( 255 );
1246 QColor endColor = color2;
1247 if ( !endColor.isValid() )
1249 endColor = startColor;
1250 endColor.setAlpha( 0 );
1254 QVariantAnimation *animation =
new QVariantAnimation(
this );
1255 connect( animation, &QVariantAnimation::finished,
this, [animation, rb]
1257 animation->deleteLater();
1260 connect( animation, &QPropertyAnimation::valueChanged,
this, [rb, geomType](
const QVariant & value )
1262 QColor
c = value.value<QColor>();
1265 rb->setFillColor( c );
1269 rb->setStrokeColor( c );
1270 QColor c = rb->secondaryStrokeColor();
1271 c.setAlpha( c.alpha() );
1272 rb->setSecondaryStrokeColor( c );
1277 animation->setDuration( duration * flashes );
1278 animation->setStartValue( endColor );
1279 double midStep = 0.2 / flashes;
1280 for (
int i = 0; i < flashes; ++i )
1282 double start =
static_cast< double >( i ) / flashes;
1283 animation->setKeyValueAt( start + midStep, startColor );
1284 double end =
static_cast< double >( i + 1 ) / flashes;
1286 animation->setKeyValueAt( end, endColor );
1288 animation->setEndValue( endColor );
1305 double dx = std::fabs( currentExtent.
width() / 4 );
1306 double dy = std::fabs( currentExtent.
height() / 4 );
1340 if ( ! e->isAutoRepeat() )
1342 QApplication::setOverrideCursor( Qt::ClosedHandCursor );
1348 case Qt::Key_PageUp:
1353 case Qt::Key_PageDown:
1360 mUseParallelRendering = !mUseParallelRendering;
1365 mDrawRenderingStats = !mDrawRenderingStats;
1396 QApplication::restoreOverrideCursor();
1410 QgsDebugMsgLevel(
"Ignoring key release: " + QString::number( e->key() ), 2 );
1429 void QgsMapCanvas::beginZoomRect( QPoint pos )
1431 mZoomRect.setRect( 0, 0, 0, 0 );
1432 QApplication::setOverrideCursor( mZoomCursor );
1433 mZoomDragging =
true;
1435 QColor color( Qt::blue );
1436 color.setAlpha( 63 );
1437 mZoomRubberBand->setColor( color );
1438 mZoomRect.setTopLeft( pos );
1441 void QgsMapCanvas::endZoomRect( QPoint pos )
1443 mZoomDragging =
false;
1444 mZoomRubberBand.reset(
nullptr );
1445 QApplication::restoreOverrideCursor();
1448 mZoomRect.setRight( pos.x() );
1449 mZoomRect.setBottom( pos.y() );
1451 if ( mZoomRect.width() < 5 && mZoomRect.height() < 5 )
1458 mZoomRect = mZoomRect.normalized();
1461 const QSize &zoomRectSize = mZoomRect.size();
1462 const QSize &canvasSize = mSettings.
outputSize();
1463 double sfx =
static_cast< double >( zoomRectSize.width() ) / canvasSize.width();
1464 double sfy =
static_cast< double >( zoomRectSize.height() ) / canvasSize.height();
1465 double sf = std::max( sfx, sfy );
1476 if ( e->button() == Qt::MidButton )
1487 && e->modifiers() & Qt::ShiftModifier )
1489 beginZoomRect( e->pos() );
1514 if ( e->button() == Qt::MidButton )
1519 else if ( e->button() == Qt::BackButton )
1524 else if ( e->button() == Qt::ForwardButton )
1531 if ( mZoomDragging && e->button() == Qt::LeftButton )
1533 endZoomRect( e->pos() );
1543 QgsDebugMsgLevel( QStringLiteral(
"Right click in map tool zoom or pan, last tool is %1." ).arg(
1544 mLastNonZoomMapTool ? QStringLiteral(
"not null" ) : QStringLiteral(
"null" ) ), 2 );
1549 if ( mLastNonZoomMapTool
1554 mLastNonZoomMapTool =
nullptr;
1574 QGraphicsView::resizeEvent( e );
1575 mResizeTimer->start( 500 );
1577 double oldScale = mSettings.
scale();
1578 QSize lastSize = viewport()->size();
1581 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
1587 double scaleFactor = oldScale / mSettings.
scale();
1590 r.
scale( scaleFactor, ¢er );
1605 QGraphicsView::paintEvent( e );
1610 const QList<QGraphicsItem *> items = mScene->items();
1611 for ( QGraphicsItem *gi : items )
1628 QgsDebugMsgLevel(
"Wheel event delta " + QString::number( e->delta() ), 2 );
1633 if ( e->isAccepted() )
1637 if ( e->delta() == 0 )
1643 double zoomFactor = e->angleDelta().y() > 0 ? 1. / zoomInFactor() : zoomOutFactor();
1646 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( e->angleDelta().y() );
1648 if ( e->modifiers() & Qt::ControlModifier )
1651 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
1654 double signedWheelFactor = e->angleDelta().y() > 0 ? 1 / zoomFactor : zoomFactor;
1659 QgsPointXY newCenter( mousePos.
x() + ( ( oldCenter.
x() - mousePos.
x() ) * signedWheelFactor ),
1660 mousePos.
y() + ( ( oldCenter.
y() - mousePos.
y() ) * signedWheelFactor ) );
1668 mWheelZoomFactor = factor;
1690 double scaleFactor = ( zoomIn ? zoomInFactor() : zoomOutFactor() );
1701 r.
scale( scaleFactor, ¢er );
1709 mScaleLocked = isLocked;
1720 else if ( mZoomDragging )
1722 mZoomRect.setBottomRight( e->pos() );
1723 mZoomRubberBand->setToCanvasRectangle( mZoomRect );
1724 mZoomRubberBand->show();
1737 if ( !panOperationInProgress() )
1754 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
1764 mLastNonZoomMapTool = mMapTool;
1768 mLastNonZoomMapTool =
nullptr;
1778 connect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
1786 if ( mMapTool && mMapTool == tool )
1788 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
1793 setCursor( Qt::ArrowCursor );
1796 if ( mLastNonZoomMapTool && mLastNonZoomMapTool == tool )
1798 mLastNonZoomMapTool =
nullptr;
1811 QBrush bgBrush( color );
1812 setBackgroundBrush( bgBrush );
1815 palette.setColor( backgroundRole(), color );
1816 setPalette( palette );
1820 mScene->setBackgroundBrush( bgBrush );
1829 return mScene->backgroundBrush().color();
1841 bool hasSelectedFeatures =
false;
1848 hasSelectedFeatures =
true;
1853 if ( hasSelectedFeatures )
1920 if ( mTheme == theme )
1934 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
1952 void QgsMapCanvas::connectNotify(
const char *signal )
1955 QgsDebugMsg(
"QgsMapCanvas connected to " + QString( signal ) );
1959 void QgsMapCanvas::layerRepaintRequested(
bool deferred )
1965 void QgsMapCanvas::autoRefreshTriggered()
1978 void QgsMapCanvas::updateAutoRefreshTimer()
1982 int minAutoRefreshInterval = -1;
1990 if ( minAutoRefreshInterval > 0 )
1992 mAutoRefreshTimer.setInterval( minAutoRefreshInterval );
1993 mAutoRefreshTimer.start();
1997 mAutoRefreshTimer.stop();
2001 void QgsMapCanvas::projectThemesChanged()
2003 if ( mTheme.isEmpty() )
2029 double dx = end.
x() - start.
x();
2030 double dy = end.
y() - start.
y();
2032 c.
set( c.
x() - dx, c.
y() - dy );
2065 setSceneRect( -pnt.x(), -pnt.y(), viewport()->size().width(), viewport()->size().height() );
2073 bool allHandled =
true;
2076 bool handled =
false;
2079 if ( handler && handler->customUriProviderKey() == uri.providerKey )
2081 if ( handler->handleCustomUriCanvasDrop( uri,
this ) )
2109 if ( !mPreviewEffect )
2114 mPreviewEffect->setEnabled( previewEnabled );
2119 if ( !mPreviewEffect )
2124 return mPreviewEffect->isEnabled();
2129 if ( !mPreviewEffect )
2134 mPreviewEffect->
setMode( mode );
2139 if ( !mPreviewEffect )
2144 return mPreviewEffect->
mode();
2149 if ( !mSnappingUtils )
2155 return mSnappingUtils;
2160 mSnappingUtils = utils;
2167 QDomNodeList nodes = doc.elementsByTagName( QStringLiteral(
"mapcanvas" ) );
2168 if ( nodes.count() )
2170 QDomNode node = nodes.item( 0 );
2173 if ( nodes.count() > 1 )
2175 for (
int i = 0; i < nodes.size(); ++i )
2177 QDomElement elementNode = nodes.at( i ).toElement();
2179 if ( elementNode.hasAttribute( QStringLiteral(
"name" ) ) && elementNode.attribute( QStringLiteral(
"name" ) ) == objectName() )
2181 node = nodes.at( i );
2189 if ( objectName() != QStringLiteral(
"theMapCanvas" ) )
2200 QDomElement elem = node.toElement();
2201 if ( elem.hasAttribute( QStringLiteral(
"theme" ) ) )
2205 setTheme( elem.attribute( QStringLiteral(
"theme" ) ) );
2208 setAnnotationsVisible( elem.attribute( QStringLiteral(
"annotationsVisible" ), QStringLiteral(
"1" ) ).toInt() );
2211 const QDomNodeList scopeElements = elem.elementsByTagName( QStringLiteral(
"expressionContextScope" ) );
2212 if ( scopeElements.size() > 0 )
2214 const QDomElement scopeElement = scopeElements.at( 0 ).toElement();
2220 QgsDebugMsg( QStringLiteral(
"Couldn't read mapcanvas information from project" ) );
2233 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
2236 QgsDebugMsg( QStringLiteral(
"Unable to find qgis element in project file" ) );
2239 QDomNode qgisNode = nl.item( 0 );
2241 QDomElement mapcanvasNode = doc.createElement( QStringLiteral(
"mapcanvas" ) );
2242 mapcanvasNode.setAttribute( QStringLiteral(
"name" ), objectName() );
2243 if ( !mTheme.isEmpty() )
2244 mapcanvasNode.setAttribute( QStringLiteral(
"theme" ), mTheme );
2245 mapcanvasNode.setAttribute( QStringLiteral(
"annotationsVisible" ), mAnnotationsVisible );
2246 qgisNode.appendChild( mapcanvasNode );
2248 mSettings.
writeXml( mapcanvasNode, doc );
2251 QDomElement scopeElement = doc.createElement( QStringLiteral(
"expressionContextScope" ) );
2253 tmpScope.
removeVariable( QStringLiteral(
"atlas_featurenumber" ) );
2259 mapcanvasNode.appendChild( scopeElement );
2274 r.
scale( scaleFactor, center );
2303 bool allHandled =
true;
2306 bool handled =
false;
2309 if ( handler->canHandleCustomUriCanvasDrop( uri,
this ) )
2329 void QgsMapCanvas::mapToolDestroyed()
2337 if ( !QTouchDevice::devices().empty() )
2339 if ( e->type() == QEvent::Gesture )
2341 if ( QTapAndHoldGesture *tapAndHoldGesture = qobject_cast< QTapAndHoldGesture * >( static_cast<QGestureEvent *>( e )->gesture( Qt::TapAndHoldGesture ) ) )
2343 QPointF pos = tapAndHoldGesture->position();
2344 pos = mapFromGlobal( QPoint( pos.x(), pos.y() ) );
2352 return mMapTool->
gestureEvent( static_cast<QGestureEvent *>( e ) );
2358 return QGraphicsView::event( e );
2384 while ( mRefreshScheduled || mJob )
2386 QgsApplication::processEvents();
2402 QList<QgsMapCanvasAnnotationItem *> annotationItemList;
2403 const QList<QGraphicsItem *> items = mScene->items();
2404 for ( QGraphicsItem *gi : items )
2409 annotationItemList.push_back( aItem );
2413 return annotationItemList;
2418 mAnnotationsVisible = show;
2422 item->setVisible( show );
2436 void QgsMapCanvas::startPreviewJobs()
2445 schedulePreviewJob( 0 );
2448 void QgsMapCanvas::startPreviewJob(
int number )
2461 double dx = ( i - 1 ) * mapRect.
width();
2462 double dy = ( 1 - j ) * mapRect.
height();
2475 const QList<QgsMapLayer *>
layers = jobSettings.
layers();
2476 QList< QgsMapLayer * > previewLayers;
2485 QgsDebugMsgLevel( QStringLiteral(
"Layer %1 not rendered because it does not match the renderInPreview criterion %2" ).arg( layer->
id() ).arg( mLastLayerRenderTime.value( layer->
id() ) ), 3 );
2489 previewLayers <<
layer;
2494 job->setProperty(
"number", number );
2495 mPreviewJobs.append( job );
2500 void QgsMapCanvas::stopPreviewJobs()
2502 mPreviewTimer.stop();
2503 const auto previewJobs = mPreviewJobs;
2504 for (
auto previewJob : previewJobs )
2510 previewJob->cancelWithoutBlocking();
2513 mPreviewJobs.clear();
2516 void QgsMapCanvas::schedulePreviewJob(
int number )
2518 mPreviewTimer.setSingleShot(
true );
2519 mPreviewTimer.setInterval( PREVIEW_JOB_DELAY_MS );
2520 disconnect( mPreviewTimerConnection );
2521 mPreviewTimerConnection = connect( &mPreviewTimer, &QTimer::timeout,
this, [ = ]()
2523 startPreviewJob( number );
2525 mPreviewTimer.start();
2528 bool QgsMapCanvas::panOperationInProgress()
2533 if (
QgsMapToolPan *panTool = qobject_cast< QgsMapToolPan *>( mMapTool ) )
2535 if ( panTool->isDragging() )
2542 int QgsMapCanvas::nextZoomLevel(
const QList<double> &resolutions,
bool zoomIn )
const 2544 int resolutionLevel = -1;
2547 for (
int i = 0, n = resolutions.size(); i < n; ++i )
2549 if (
qgsDoubleNear( resolutions[i], currentResolution, 0.0001 ) )
2551 resolutionLevel = zoomIn ? ( i - 1 ) : ( i + 1 );
2554 else if ( currentResolution <= resolutions[i] )
2556 resolutionLevel = zoomIn ? ( i - 1 ) : i;
2560 return ( resolutionLevel < 0 || resolutionLevel >= resolutions.size() ) ? -1 : resolutionLevel;
2563 double QgsMapCanvas::zoomInFactor()
const 2565 if ( !mZoomResolutions.isEmpty() )
2567 int zoomLevel = nextZoomLevel( mZoomResolutions,
true );
2568 if ( zoomLevel != -1 )
2573 return 1 / mWheelZoomFactor;
2576 double QgsMapCanvas::zoomOutFactor()
const 2578 if ( !mZoomResolutions.isEmpty() )
2580 int zoomLevel = nextZoomLevel( mZoomResolutions,
false );
2581 if ( zoomLevel != -1 )
2586 return mWheelZoomFactor;
void unsetMapTool(QgsMapTool *mapTool)
Unset the current map tool or last non zoom tool.
bool previewJobsEnabled() const
Returns true if canvas map preview jobs (low priority render jobs which render portions of the view j...
bool setReferencedExtent(const QgsReferencedRectangle &extent) SIP_THROW(QgsCsException)
Sets the canvas to the specified extent.
QgsUnitTypes::DistanceUnit lengthUnits() const
Returns the units of distance for length calculations made by this object.
The class is used as a container of context for various read/write operations on other objects...
static QgsSvgCache * svgCache()
Returns the application's SVG cache, used for caching SVG images and handling parameter replacement w...
Wrapper for iterator of features from vector data provider or vector layer.
void updateCanvasItemPositions()
called on resize or changed extent to notify canvas items to change their rectangle ...
void finished()
emitted when asynchronous rendering is finished (or canceled).
void setParallelRenderingEnabled(bool enabled)
Set whether the layers are rendered in parallel or sequentially.
void set(double x, double y)
Sets the x and y value of the point.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
sets destination coordinate reference system
QPoint mouseLastXY
Last seen point of the mouse.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns global labeling engine settings from the internal map settings.
A rectangle specified with double values.
Base class for all map layer types.
void setExtent(const QgsRectangle &rect, bool magnified=true)
Set coordinates of the rectangle which should be rendered.
Job implementation that renders everything sequentially using a custom painter.
std::unique_ptr< CanvasProperties > mCanvasProperties
Handle pattern for implementation object.
virtual bool isEmpty() const
Returns true if the geometry is empty.
void setRotation(double degrees)
Set the rotation of the map canvas in clockwise degrees.
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) ...
QList< QgsMapCanvasAnnotationItem * > annotationItems() const
Returns a list of all annotation items in the canvas.
QSet< QgsFeatureId > QgsFeatureIds
void zoomToNextExtent()
Zoom to the next extent (view)
bool hasMapTheme(const QString &name) const
Returns whether a map theme with a matching name exists.
void zoomWithCenter(int x, int y, bool zoomIn)
Zooms in/out with a given center.
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 setMinimal()
Set a rectangle so that min corner is at max and max corner is at min.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the coordinate transform context, which stores various information regarding which datum transfo...
QList< QgsMapLayer * > layers() const
Returns the list of layers shown within the map canvas.
void panActionStart(QPoint releasePoint)
Starts a pan action.
void readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads scope variables from an XML element.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the stored overrides of styles for rendering layers.
double magnificationFactor() const
Returns the magnification factor.
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
void setXMaximum(double x)
Set the maximum x value.
void clearExtentHistory()
This class is a composition of two QSettings instances:
Maximum angle between generating radii (lines from arc center to output vertices) ...
bool event(QEvent *e) override
QColor selectionColor() const
Returns color for selected features.
bool mouseButtonDown
Flag to indicate status of mouse button.
void wheelEvent(QWheelEvent *e) override
void canvasColorChanged()
Emitted when canvas background color changes.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
QgsReferencedRectangle defaultViewExtent() const
Returns the default view extent, which should be used as the initial map extent when this project is ...
void stopRendering()
stop rendering (if there is any right now)
static UriList decodeUriList(const QMimeData *data)
static void warning(const QString &msg)
Goes to qWarning.
void setPreviewJobsEnabled(bool enabled)
Sets whether canvas map preview jobs (low priority render jobs which render portions of the view just...
static QgsImageCache * imageCache()
Returns the application's image cache, used for caching resampled versions of raster images...
A class to represent a 2D point.
double rotation() const
Gets the current map canvas rotation in clockwise degrees.
QgsPreviewEffect::PreviewMode previewMode() const
Returns the current preview mode for the map canvas.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
void dropEvent(QDropEvent *event) override
QColor backgroundColor() const
Gets the background color of the map.
void keyPressEvent(QKeyEvent *e) override
void zoomToFeatureExtent(QgsRectangle &rect)
Zooms to feature extent.
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
void enableAntiAliasing(bool flag)
used to determine if anti-aliasing is enabled or not
An abstract class for items that can be placed on the map canvas.
void setCurrentLayer(QgsMapLayer *layer)
int layerCount() const
Returns number of layers on the map.
Errors errors() const
List of errors that happened during the rendering job - available when the rendering has been finishe...
void moveCanvasContents(bool reset=false)
called when panning is in action, reset indicates end of panning
A QgsMapMouseEvent is the result of a user interaction with the mouse on a QgsMapCanvas.
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
void setFlags(QgsMapSettings::Flags flags)
Sets combination of flags that will be used for rendering.
void setAnnotationsVisible(bool visible)
Sets whether annotations are visible in the canvas.
constexpr double CANVAS_MAGNIFICATION_MAX
Maximum magnification level allowed in map canvases.
void readProject(const QDomDocument &)
called to read map canvas settings from project
bool panSelectorDown
Flag to indicate the pan selector key is held down by user.
void refresh()
Repaints the canvas map.
A geometry is the spatial representation of a feature.
void tapAndHoldGestureOccurred(const QgsPointXY &mapPoint, QTapAndHoldGesture *gesture)
Emitted whenever a tap and hold gesture occurs at the specified map point.
void renderComplete(QPainter *)
Emitted when the canvas has rendered.
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
Snapping utils instance that is connected to a canvas and updates the configuration (map settings + c...
Abstract base class for spatial data provider implementations.
bool isCachingEnabled() const
Check whether images of rendered layers are curerently being cached.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
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...
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
QgsMapTool * mapTool()
Returns the currently active tool.
SegmentationToleranceType
Segmentation tolerance as maximum angle or maximum difference between approximation and circle...
QList< QgsMapLayer * > layers() const
Gets list of layers for map rendering The layers are stored in the reverse order of how they are rend...
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
const QgsCoordinateReferenceSystem & crs
void mousePressEvent(QMouseEvent *e) override
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void mapThemesChanged()
Emitted when map themes within the collection are changed.
static QgsExpressionContextScope * atlasScope(const QgsLayoutAtlas *atlas)
Creates a new scope which contains variables and functions relating to a QgsLayoutAtlas.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
virtual QImage renderedImage()=0
Gets a preview/resulting image.
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
int renderingTime() const
Returns the total time it took to finish the job (in milliseconds).
Map canvas is a class for displaying all GIS data types on a canvas.
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes takes output image size into accou...
QgsExpressionContextScope * defaultExpressionContextScope()
Creates a new scope which contains default variables and functions relating to the map canvas...
void selectionChanged(QgsVectorLayer *layer)
Emitted when selection in any layer gets changed.
Abstract base class that may be implemented to handle new types of data to be dropped in QGIS...
Enable drawing of labels on top of the map.
static QString worldFileContent(const QgsMapSettings &mapSettings)
Creates the content of a world file.
double maxRenderingTimeMs
Default maximum allowable render time, in ms.
void zoomLastStatusChanged(bool)
Emitted when zoom last status changed.
A graphics effect which can be applied to a widget to simulate various printing and color blindness m...
QgsCoordinateReferenceSystem destinationCrs() const
returns CRS of destination coordinate reference system
void setCache(QgsMapRendererCache *cache)
Assign a cache to be used for reading and storing rendered images of individual layers.
void magnificationChanged(double)
Emitted when the scale of the map changes.
void setFlag(Flag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected)
void updateScale()
Emits signal scaleChanged to update scale in main window.
QgsUnitTypes::DistanceUnit mapUnits() const
Gets units of map's geographical coordinates - used for scale calculation.
static bool isUriList(const QMimeData *data)
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
sets destination coordinate reference system
The QgsMapSettings class contains configuration for rendering of the map.
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 resizeEvent(QResizeEvent *e) override
Deprecated to be deleted, stuff from here should be moved elsewhere.
double sqrDist(double x, double y) const
Returns the squared distance between this point a specified x, y coordinate.
void enableMapTileRendering(bool flag)
sets map tile rendering flag
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
QgsCoordinateReferenceSystem crs() const
Returns the associated coordinate reference system, or an invalid CRS if no reference system is set...
Perform transforms between map coordinates and device coordinates.
void setSnappingUtils(QgsSnappingUtils *utils)
Assign an instance of snapping utils to the map canvas.
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
bool removeVariable(const QString &name)
Removes a variable from the context scope, if found.
void mapThemeChanged(const QString &theme)
Emitted when a map theme changes definition.
Q_INVOKABLE QgsRectangle boundingBoxOfSelected() const
Returns the bounding box of the selected features. If there is no selection, QgsRectangle(0,0,0,0) is returned.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
void setMapTool(QgsMapTool *mapTool, bool clean=false)
Sets the map tool currently being used on the canvas.
void setOutputSize(QSize size)
Sets the size of the resulting map image.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context...
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
double mapUnitsPerPixel() const
Returns the mapUnitsPerPixel (map units per pixel) for the canvas.
void start() override
Start the rendering job and immediately return.
void saveAsImage(const QString &fileName, QPixmap *QPixmap=nullptr, const QString &="PNG")
Save the contents of the map canvas to disk as an image.
QgsMapThemeCollection mapThemeCollection
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets global labeling engine settings in the internal map settings.
void mapCanvasRefreshed()
Emitted when canvas finished a refresh request.
void rotationChanged(double)
Emitted when the rotation of the map changes.
#define QgsDebugMsgLevel(str, level)
void setMagnificationFactor(double factor)
Set the magnification factor.
void zoomNextStatusChanged(bool)
Emitted when zoom next status changed.
bool isEmpty() const
Returns true if the rectangle is empty.
A circle is used to highlight points (â—‹)
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 clearCache()
Make sure to remove any rendered images from cache (does nothing if cache is not enabled) ...
void reload() FINAL
Synchronises with changes in the datasource.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsMapCanvas(QWidget *parent=nullptr)
Constructor.
A class for drawing transient features (e.g.
double scale() const
Returns the calculated map scale.
Job implementation that renders all layers in parallel.
double width() const
Returns the width of the rectangle.
void setYMinimum(double y)
Set the minimum y value.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
void setMapUpdateInterval(int timeMilliseconds)
Set how often map preview should be updated while it is being rendered (in milliseconds) ...
void keyReleased(QKeyEvent *e)
Emit key release event.
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).
virtual void waitForFinished()=0
Block until the job has finished.
double mapUnitsPerPixel() const
Returns the distance in geographical coordinates that equals to one pixel in the map.
void setDevicePixelRatio(float dpr)
Sets the device pixel ratio Common values are 1 for normal-dpi displays and 2 for high-dpi "retina" d...
void readProject(const QDomDocument &)
Emitted when a project is being read.
Enable anti-aliasing for map rendering.
QgsRectangle extent() const
Returns the current zoom extent of the map canvas.
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
void mouseDoubleClickEvent(QMouseEvent *e) override
This class wraps a request for features to a vector layer (or directly its vector data provider)...
void panToSelected(QgsVectorLayer *layer=nullptr)
Pan to the selected features of current (vector) layer keeping same extent.
void setCustomDropHandlers(const QVector< QPointer< QgsCustomDropHandler >> &handlers)
Sets a list of custom drop handlers to use when drop events occur on the canvas.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
QgsRectangle layerExtentToOutputExtent(const QgsMapLayer *layer, QgsRectangle extent) const
transform bounding box from layer's CRS to output CRS
void setWheelFactor(double factor)
Sets wheel zoom factor (should be greater than 1)
Encapsulates a QGIS project, including sets of map layers and their styles, layouts, annotations, canvases, etc.
void destinationCrsChanged()
Emitted when map CRS has changed.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
bool hasValidSettings() const
Check whether the map settings are valid and can be used for rendering.
bool isFrozen() const
Returns true if canvas is frozen.
A QgsRectangle with associated coordinate reference system.
void setCachingEnabled(bool enabled)
Set whether to cache images of rendered layers.
Single scope for storing variables and functions for use within a QgsExpressionContext.
const QgsProjectViewSettings * viewSettings() const
Returns the project's view settings, which contains settings and properties relating to how a QgsProj...
double mapUnitsPerPixel() const
Returns current map units per pixel.
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.
void transformContextChanged()
Emitted when the canvas transform context is changed.
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes scope variables to an XML element.
void setMode(PreviewMode mode)
Sets the mode for the preview effect, which controls how the effect modifies a widgets appearance...
void renderStarting()
Emitted when the canvas is about to be rendered.
float devicePixelRatio() const
Returns device pixel ratio Common values are 1 for normal-dpi displays and 2 for high-dpi "retina" di...
const QgsMapToPixel & mapToPixel() const
void keyPressed(QKeyEvent *e)
Emit key press event.
void currentLayerChanged(QgsMapLayer *layer)
Emitted when the current layer is changed.
void zoomOut()
Zoom out with fixed factor.
Enable drawing of vertex markers for layers in editing mode.
void waitWhileRendering()
Blocks until the rendering job has finished.
constexpr double CANVAS_MAGNIFICATION_MIN
Minimum magnification level allowed in map canvases.
void zoomToPreviousExtent()
Zoom to the previous extent (view)
bool isDrawing()
Find out whether rendering is in progress.
void zoomByFactor(double scaleFactor, const QgsPointXY *center=nullptr)
Zoom with the factor supplied.
virtual bool renderInPreview(const QgsDataProvider::PreviewContext &context)
Returns whether the layer must be rendered in preview jobs.
void zoomToSelected(QgsVectorLayer *layer=nullptr)
Zoom to the extent of the selected features of provided (vector) layer.
A class to represent a vector.
PreviewMode mode() const
Returns the mode used for the preview effect.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
void setPreviewModeEnabled(bool previewEnabled)
Enables a preview mode for the map canvas.
virtual void start()=0
Start the rendering job and immediately return.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QPoint mouseLastXY()
returns last position of mouse cursor
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double magnificationFactor() const
Returns the magnification factor.
void setRotation(double rotation)
Sets the rotation of the resulting map image, in degrees clockwise.
QgsMapLayer * currentLayer()
returns current layer (set by legend widget)
QMap< QString, QString > layerStyleOverrides() const
Returns the stored overrides of styles for layers.
void mouseMoveEvent(QMouseEvent *e) override
void keyReleaseEvent(QKeyEvent *e) override
DistanceUnit
Units of distance.
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 scale() const
Returns the last reported scale of the canvas.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle...
void remoteImageFetched(const QString &url)
Emitted when the cache has finished retrieving an image file from a remote url.
QColor canvasColor() const
Read property of QColor bgColor.
void clear()
Invalidates the cache contents, clearing all cached images.
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
void selectionChangedSlot()
Receives signal about selection change, and pass it on with layer info.
Draw map such that there are no problems between adjacent tiles.
Job implementation that renders everything sequentially in one thread.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations...
Render is a 'canvas preview' render, and shortcuts should be taken to ensure fast rendering...
QgsUnitTypes::DistanceUnit mapUnits() const
Convenience function for returning the current canvas map units.
void setBackgroundColor(const QColor &color)
Sets the background color of the map.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets the global configuration of the labeling engine.
void mouseReleaseEvent(QMouseEvent *e) override
void writeProject(QDomDocument &)
Emitted when the project is being written.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
QMap< QString, QString > layerStyleOverrides() const
Gets map of map layer style overrides (key: layer ID, value: style name) where a different style shou...
void zoomToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids)
Set canvas extent to the bounding box of a set of features.
static QgsExpressionContextScope * mapSettingsScope(const QgsMapSettings &mapSettings)
Creates a new scope which contains variables and functions relating to a QgsMapSettings object...
QString theme() const
Returns the map's theme shown in the canvas, if set.
QgsPointXY center() const
Gets map center, in geographical coordinates.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
void setSelectionColor(const QColor &color)
Sets color that is used for drawing of selected vector features.
void layerStyleOverridesChanged()
Emitted when the configuration of overridden layer styles changes.
void dragEnterEvent(QDragEnterEvent *e) override
void setYMaximum(double y)
Set the maximum y value.
QgsPointXY layerToMapCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from layer's CRS to output CRS
void writeProject(QDomDocument &)
called to write map canvas settings to project
void panAction(QMouseEvent *event)
Called when mouse is moving and pan is activated.
void setLayers(const QList< QgsMapLayer *> &layers)
Sets the list of layers that should be shown in the canvas.
QgsRectangle fullExtent() const
returns current extent of layer set
Intermediate base class adding functionality that allows client to query the rendered image...
void panToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids, bool alwaysRecenter=true)
Centers canvas extent to feature ids.
Stores global configuration for labeling engine.
static QgsProject * instance()
Returns the QgsProject singleton instance.
void zoomToFullExtent()
Zoom to the full extent of all layers.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
This class represents a coordinate reference system (CRS).
QgsRectangle fullExtent() const
Returns the combined extent for all layers on the map canvas.
This class has all the configuration of snapping and can return answers to snapping queries...
const QgsLabelingResults * labelingResults() const
Gets access to the labeling results (may be nullptr)
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
void setMapSettingsFlags(QgsMapSettings::Flags flags)
Resets the flags for the canvas' map settings.
void refreshAllLayers()
Reload all layers (including refreshing layer properties from their data sources), clears the cache and refreshes the canvas.
QgsFeatureRequest & setLimit(long limit)
Set the maximum number of features to request.
QList< QgsMimeDataUtils::Uri > UriList
void zoomScale(double scale)
Zooms the canvas to a specific scale.
void setExtent(const QgsRectangle &r, bool magnified=false)
Sets the extent of the map canvas.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
void setLayers(const QList< QgsMapLayer *> &layers)
Set list of layers for map rendering.
const QgsMapToPixel * getCoordinateTransform()
Gets the current coordinate transform.
void scaleChanged(double)
Emitted when the scale of the map changes.
void renderErrorOccurred(const QString &error, QgsMapLayer *layer)
Emitted whenever an error is encountered during a map render operation.
void setPathResolver(const QgsPathResolver &resolver)
Sets the path resolver for conversion between relative and absolute paths during rendering operations...
T enumValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on an enum.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
virtual void cancelWithoutBlocking()=0
Triggers cancellation of the rendering job without blocking.
double yMaximum() const
Returns the y maximum value (top side of rectangle).
void setSelectionColor(const QColor &color)
Set color of selected vector features.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
void paintEvent(QPaintEvent *e) override
void layerStateChange()
This slot is connected to the visibility change of one or more layers.
double lastRenderingTimeMs
Previous rendering time for the layer, in ms.
Enable vector simplification and other rendering optimizations.
static QCursor getThemeCursor(Cursor cursor)
Helper to get a theme cursor.
void freeze(bool frozen=true)
Freeze/thaw the map canvas.
void setScaleLocked(bool isLocked)
Lock the scale, so zooming can be performed using magnication.
Class that stores computed placement from labeling engine.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
void remoteSvgFetched(const QString &url)
Emitted when the cache has finished retrieving an SVG file from a remote url.
This class is responsible for keeping cache of rendered images resulting from a map rendering job...
bool testFlag(Flag flag) const
Check whether a particular flag is enabled.
void transformContextChanged()
Emitted when the project transformContext() is changed.
Custom exception class for Coordinate Reference System related exceptions.
void setTheme(const QString &theme)
Sets a map theme to show in the canvas.
QColor selectionColor() const
Gets color that is used for drawing of selected vector features.
QgsPointXY center() const
Returns the center point of the rectangle.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
void readXml(QDomNode &node)
bool nextFeature(QgsFeature &f)
QPoint rubberStartPoint
Beginning point of a rubber band.
bool hasAutoRefreshEnabled() const
Returns true if auto refresh is enabled for the layer.
double bearing(const QgsPointXY &p1, const QgsPointXY &p2) const
Computes the bearing (in radians) between two points.
QgsSnappingUtils * snappingUtils() const
Returns snapping utility class that is associated with map canvas.
virtual QgsLabelingResults * takeLabelingResults()=0
Gets pointer to internal labeling engine (in order to get access to the results). ...
void xyCoordinates(const QgsPointXY &p)
Emits current mouse position.
void autoRefreshIntervalChanged(int interval)
Emitted when the auto refresh interval changes.
void writeXml(QDomNode &node, QDomDocument &doc)
void zoomIn()
Zoom in with fixed factor.
Stores settings related to the context in which a preview job runs.
QgsPointXY mapToLayerCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from output CRS to layer's CRS
void waitForFinished() override
Block until the job has finished.
Represents a vector layer which manages a vector based data sets.
virtual void updatePosition()
called on changed extent or resize event to update position of the item
bool isParallelRenderingEnabled() const
Check whether the layers are rendered in parallel or sequentially.
const QgsMapSettings & mapSettings() const
Returns map settings with which this job was started.
void mapToolSet(QgsMapTool *newTool, QgsMapTool *oldTool)
Emit map tool changed with the old tool.
CanvasProperties()=default
Constructor for CanvasProperties.
An interactive map canvas item which displays a QgsAnnotation.
void themeChanged(const QString &theme)
Emitted when the canvas has been assigned a different map theme.
void extentsChanged()
Emitted when the extents of the map change.
QSize outputSize() const
Returns the size of the resulting map image.
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
void panDistanceBearingChanged(double distance, QgsUnitTypes::DistanceUnit unit, double bearing)
Emitted whenever the distance or bearing of an in-progress panning operation is changed.
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
QgsMapLayer * layer(int index)
Returns the map layer at position index in the layer stack.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
virtual bool isActive() const =0
Tell whether the rendering job is currently running in background.
void setXMinimum(double x)
Set the minimum x value.
QgsCoordinateReferenceSystem crs
double height() const
Returns the height of the rectangle.
void setMagnificationFactor(double factor)
Sets the factor of magnification to apply to the map canvas.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
void panActionEnd(QPoint releasePoint)
Ends pan action and redraws the canvas.
void redrawAllLayers()
Clears all cached images and redraws all layers.
bool previewModeEnabled() const
Returns whether a preview mode is enabled for the map canvas.
void layersChanged()
Emitted when a new set of layers has been received.
void messageEmitted(const QString &title, const QString &message, Qgis::MessageLevel=Qgis::Info)
emit a message (usually to be displayed in a message bar)
virtual bool usedCachedLabels() const =0
Returns true if the render job was able to use a cached labeling solution.