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>
42 #include <QVariantAnimation>
43 #include <QPropertyAnimation>
123 : QGraphicsView( parent )
125 , mExpressionContextScope( tr(
"Map Canvas" ) )
127 mScene =
new QGraphicsScene();
129 setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
130 setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
131 setMouseTracking(
true );
132 setFocusPolicy( Qt::StrongFocus );
134 mResizeTimer =
new QTimer(
this );
135 mResizeTimer->setSingleShot(
true );
138 mRefreshTimer =
new QTimer(
this );
139 mRefreshTimer->setSingleShot(
true );
140 connect( mRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::refreshMap );
143 mMap =
new QgsMapCanvasMap(
this );
183 setDestinationCrs( crs );
196 double segmentationTolerance = settings.
value( QStringLiteral(
"qgis/segmentationTolerance" ),
"0.01745" ).toDouble();
201 mWheelZoomFactor = settings.
value( QStringLiteral(
"qgis/zoom_factor" ), 2 ).toDouble();
203 QSize s = viewport()->size();
206 setSceneRect( 0, 0, s.width(), s.height() );
207 mScene->setSceneRect( QRectF( 0, 0, s.width(), s.height() ) );
212 if ( window()->windowHandle() )
214 connect( window()->windowHandle(), &QWindow::screenChanged,
this, [ = ]( QScreen * ) {mSettings.
setDevicePixelRatio( devicePixelRatio() );} );
215 connect( window()->windowHandle()->screen(), &QScreen::physicalDotsPerInchChanged,
this, [ = ]( qreal ) {mSettings.
setDevicePixelRatio( devicePixelRatio() );} );
218 connect( &mMapUpdateTimer, &QTimer::timeout,
this, &QgsMapCanvas::mapUpdateTimeout );
219 mMapUpdateTimer.setInterval( 250 );
224 grabGesture( Qt::PinchGesture );
225 grabGesture( Qt::TapAndHoldGesture );
226 viewport()->setAttribute( Qt::WA_AcceptTouchEvents );
230 viewport()->setGraphicsEffect( mPreviewEffect );
234 connect( &mAutoRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::autoRefreshTriggered );
238 setInteractive(
false );
257 mLastNonZoomMapTool =
nullptr;
267 QList< QgsMapRendererQImageJob * >::const_iterator previewJob = mPreviewJobs.constBegin();
268 for ( ; previewJob != mPreviewJobs.constEnd(); ++previewJob )
280 qDeleteAll( mScene->items() );
282 mScene->deleteLater();
285 delete mLabelingResults;
293 factor = qBound( magnifierMin, factor, magnifierMax );
322 if ( index >= 0 && index <
layers.size() )
330 if ( mCurrentLayer ==
layer )
333 mCurrentLayer =
layer;
344 return nullptr != mJob;
357 if ( !mTheme.isEmpty() )
360 setLayersPrivate(
layers );
363 void QgsMapCanvas::setLayersPrivate(
const QList<QgsMapLayer *> &layers )
365 QList<QgsMapLayer *> oldLayers = mSettings.
layers();
368 if (
layers == oldLayers )
371 const auto constOldLayers = oldLayers;
384 const auto constLayers =
layers;
400 updateAutoRefreshTimer();
428 QgsDebugMsg( QStringLiteral(
"Transform error caught: %1" ).arg( e.
what() ) );
436 mBlockItemPositionUpdates++;
438 mBlockItemPositionUpdates--;
445 QgsDebugMsgLevel( QStringLiteral(
"refreshing after destination CRS changed" ), 2 );
456 mController = controller;
474 return mLabelingResults;
501 return nullptr != mCache;
512 mUseParallelRendering = enabled;
517 return mUseParallelRendering;
522 mMapUpdateTimer.setInterval( timeMilliseconds );
527 return mMapUpdateTimer.interval();
533 return mCurrentLayer;
548 QgsDebugMsgLevel( QStringLiteral(
"CANVAS refresh - invalid settings -> nothing to do" ), 2 );
552 if ( !mRenderFlag || mFrozen )
558 if ( mRefreshScheduled )
560 QgsDebugMsgLevel( QStringLiteral(
"CANVAS refresh already scheduled" ), 2 );
564 mRefreshScheduled =
true;
569 mRefreshTimer->start( 1 );
572 void QgsMapCanvas::refreshMap()
574 Q_ASSERT( mRefreshScheduled );
589 expressionContext << generator->createExpressionContextScope();
597 if ( !mTheme.isEmpty() )
610 QList<QgsMapLayer *> allLayers = renderSettings.
layers();
616 mJobCanceled =
false;
617 if ( mUseParallelRendering )
634 mRefreshScheduled =
false;
636 mMapUpdateTimer.start();
641 void QgsMapCanvas::mapThemeChanged(
const QString &theme )
643 if (
theme == mTheme )
648 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
661 void QgsMapCanvas::mapThemeRenamed(
const QString &theme,
const QString &newTheme )
663 if ( mTheme.isEmpty() ||
theme != mTheme )
672 void QgsMapCanvas::rendererJobFinished()
674 QgsDebugMsgLevel( QStringLiteral(
"CANVAS finish! %1" ).arg( !mJobCanceled ), 2 );
676 mMapUpdateTimer.stop();
679 const auto constErrors = mJob->
errors();
693 delete mLabelingResults;
704 if ( settings.
value( QStringLiteral(
"Map/logCanvasRefreshEvent" ),
false ).toBool() )
706 QString logMsg = tr(
"Canvas refresh: %1 ms" ).arg( mJob->
renderingTime() );
710 if ( mDrawRenderingStats )
712 int w = img.width(), h = img.height();
713 QFont fnt = p.font();
716 int lh = p.fontMetrics().height() * 2;
717 QRect r( 0, h - lh, w, lh );
718 p.setPen( Qt::NoPen );
719 p.setBrush( QColor( 0, 0, 0, 110 ) );
721 p.setPen( Qt::white );
722 QString msg = QStringLiteral(
"%1 :: %2 ms" ).arg( mUseParallelRendering ? QStringLiteral(
"PARALLEL" ) : QStringLiteral(
"SEQUENTIAL" ) ).arg( mJob->
renderingTime() );
723 p.drawText( r, msg, QTextOption( Qt::AlignCenter ) );
728 mMap->setContent( img, imageRect( img, mSettings ) );
730 mLastLayerRenderTime.clear();
732 for (
auto it = times.constBegin(); it != times.constEnd(); ++it )
734 mLastLayerRenderTime.insert( it.key()->id(), it.value() );
736 if ( mUsePreviewJobs && !mRefreshAfterJob )
741 mRefreshAfterJob =
false;
751 if ( mRefreshAfterJob )
753 mRefreshAfterJob =
false;
754 clearTemporalCache();
755 clearElevationCache();
760 void QgsMapCanvas::previewJobFinished()
768 mPreviewJobs.removeAll( job );
770 int number = job->property(
"number" ).toInt();
773 startPreviewJob( number + 1 );
790 QgsLogger::warning( QStringLiteral(
"The renderer map has a wrong device pixel ratio" ) );
794 QgsRectangle rect( topLeft.
x(), topLeft.
y(), topLeft.
x() + img.width()*res, topLeft.
y() - img.height()*res );
800 return mUsePreviewJobs;
805 mUsePreviewJobs = enabled;
810 mDropHandlers = handlers;
813 void QgsMapCanvas::clearTemporalCache()
831 void QgsMapCanvas::clearElevationCache()
851 const QgsPointXY mapPoint =
event->originalMapPoint();
855 QMenu *copyCoordinateMenu =
new QMenu( tr(
"Copy Coordinate" ), &menu );
863 const QgsPointXY transformedPoint = ct.transform( mapPoint );
866 int displayPrecision = 0;
872 displayPrecision = 0;
874 displayPrecision = 1;
876 displayPrecision = 2;
878 displayPrecision = 3;
880 displayPrecision = 4;
882 displayPrecision = 5;
884 displayPrecision = 6;
886 displayPrecision = 7;
888 displayPrecision = 8;
890 displayPrecision = 9;
897 QAction *copyCoordinateAction =
new QAction( QStringLiteral(
"%3 (%1, %2)" ).arg(
898 QString::number( transformedPoint.
x(),
'f', displayPrecision ),
899 QString::number( transformedPoint.
y(),
'f', displayPrecision ),
900 identifier ), &menu );
902 connect( copyCoordinateAction, &QAction::triggered,
this, [displayPrecision, transformedPoint]
904 QClipboard *clipboard = QApplication::clipboard();
906 const QString coordinates = QString::number( transformedPoint.
x(),
'f', displayPrecision ) +
',' + QString::number( transformedPoint.
y(),
'f', displayPrecision );
909 if ( clipboard->supportsSelection() )
911 clipboard->setText( coordinates, QClipboard::Selection );
913 clipboard->setText( coordinates, QClipboard::Clipboard );
916 copyCoordinateMenu->addAction( copyCoordinateAction );
929 const QString customCrsString = settings.
value( QStringLiteral(
"qgis/custom_coordinate_crs" ) ).toString();
930 if ( !customCrsString.isEmpty() )
938 copyCoordinateMenu->addSeparator();
939 QAction *setCustomCrsAction =
new QAction( tr(
"Set Custom CRS…" ), &menu );
940 connect( setCustomCrsAction, &QAction::triggered,
this, [ = ]
944 if ( selector.exec() )
949 copyCoordinateMenu->addAction( setCustomCrsAction );
951 menu.addMenu( copyCoordinateMenu );
959 menu.exec(
event->globalPos() );
968 mSettings.
setIsTemporal( dateTimeRange.begin().isValid() || dateTimeRange.end().isValid() );
975 clearTemporalCache();
977 autoRefreshTriggered();
987 mInteractionBlockers.append( blocker );
992 mInteractionBlockers.removeAll( blocker );
999 if ( block->blockCanvasInteraction( interaction ) )
1005 void QgsMapCanvas::mapUpdateTimeout()
1010 mMap->setContent( img, imageRect( img, mSettings ) );
1019 mJobCanceled =
true;
1040 image = theQPixmap->toImage();
1041 painter.begin( &image );
1051 image = mMap->contentImage().copy();
1052 painter.begin( &image );
1056 QStyleOptionGraphicsItem option;
1057 option.initFrom(
this );
1058 QGraphicsItem *item =
nullptr;
1059 QListIterator<QGraphicsItem *> i( items() );
1061 while ( i.hasPrevious() )
1063 item = i.previous();
1072 QPointF itemScenePos = item->scenePos();
1073 painter.translate( itemScenePos.x(), itemScenePos.y() );
1075 item->paint( &painter, &option );
1079 image.save( fileName, format.toLocal8Bit().data() );
1081 QFileInfo myInfo = QFileInfo( fileName );
1084 QString outputSuffix = myInfo.suffix();
1085 QString myWorldFileName = myInfo.absolutePath() +
'/' + myInfo.completeBaseName() +
'.'
1086 + outputSuffix.at( 0 ) + outputSuffix.at( myInfo.suffix().size() - 1 ) +
'w';
1087 QFile myWorldFile( myWorldFileName );
1088 if ( !myWorldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
1092 QTextStream myStream( &myWorldFile );
1123 if ( ( r == current ) && magnified )
1136 QgsDebugMsgLevel( QStringLiteral(
"Empty extent - keeping old scale with new center!" ), 2 );
1144 if ( mScaleLocked && magnified )
1146 ScaleRestorer restorer(
this );
1163 for (
int i = mLastExtent.size() - 1; i > mLastExtentIndex; i-- )
1165 mLastExtent.removeAt( i );
1168 mLastExtent.append(
extent() );
1171 if ( mLastExtent.size() > 100 )
1173 mLastExtent.removeAt( 0 );
1177 mLastExtentIndex = mLastExtent.size() - 1;
1225 return mCursorPoint;
1269 if ( mLastExtentIndex > 0 )
1272 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
1285 if ( mLastExtentIndex < mLastExtent.size() - 1 )
1288 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
1300 mLastExtent.clear();
1301 mLastExtent.append(
extent() ) ;
1302 mLastExtentIndex = mLastExtent.size() - 1;
1320 double closestSquaredDistance = pow( extentRect.
width(), 2.0 ) + pow( extentRect.
height(), 2.0 );
1321 bool pointFound =
false;
1325 double sqrDist = point.
sqrDist( centerLayerCoordinates );
1326 if ( sqrDist > closestSquaredDistance || sqrDist < 4 * std::numeric_limits<double>::epsilon() )
1329 closestPoint = point;
1330 closestSquaredDistance = sqrDist;
1336 rect.scale( scaleFactor, &
center );
1349 layer = qobject_cast<QgsVectorLayer *>( mCurrentLayer );
1369 rect = optimalExtentForPointLayer(
layer, rect.
center() );
1388 rect =
layer->boundingBoxOfSelected();
1396 rect = optimalExtentForPointLayer(
layer, rect.
center() );
1401 if ( selectionExtent.
isNull() )
1412 return mSettings.
zRange();
1427 clearElevationCache();
1429 autoRefreshTriggered();
1465 if ( boundingBoxOfFeatureIds( ids,
layer, bbox, errorMsg ) )
1469 bbox = optimalExtentForPointLayer(
layer, bbox.
center() );
1489 if ( boundingBoxOfFeatureIds( ids,
layer, bbox, errorMsg ) )
1506 int featureCount = 0;
1514 errorMsg = tr(
"Feature does not have a geometry" );
1518 errorMsg = tr(
"Feature geometry is empty" );
1520 if ( !errorMsg.isEmpty() )
1529 if ( featureCount != ids.count() )
1531 errorMsg = tr(
"Feature not found" );
1543 layer = qobject_cast<QgsVectorLayer *>( mCurrentLayer );
1575 rect =
layer->boundingBoxOfSelected();
1583 rect = optimalExtentForPointLayer(
layer, rect.
center() );
1588 if ( selectionExtent.
isNull() )
1599 const QColor &color1,
const QColor &color2,
1600 int flashes,
int duration )
1607 QList< QgsGeometry > geoms;
1623 if ( geometries.isEmpty() )
1641 QColor startColor = color1;
1642 if ( !startColor.isValid() )
1652 startColor.setAlpha( 255 );
1654 QColor endColor = color2;
1655 if ( !endColor.isValid() )
1657 endColor = startColor;
1658 endColor.setAlpha( 0 );
1662 QVariantAnimation *animation =
new QVariantAnimation(
this );
1663 connect( animation, &QVariantAnimation::finished,
this, [animation, rb]
1665 animation->deleteLater();
1668 connect( animation, &QPropertyAnimation::valueChanged,
this, [rb, geomType](
const QVariant & value )
1670 QColor
c = value.value<QColor>();
1679 c.setAlpha(
c.alpha() );
1685 animation->setDuration( duration * flashes );
1686 animation->setStartValue( endColor );
1687 double midStep = 0.2 / flashes;
1688 for (
int i = 0; i < flashes; ++i )
1690 double start =
static_cast< double >( i ) / flashes;
1691 animation->setKeyValueAt( start + midStep, startColor );
1692 double end =
static_cast< double >( i + 1 ) / flashes;
1694 animation->setKeyValueAt( end, endColor );
1696 animation->setEndValue( endColor );
1713 double dx = std::fabs( currentExtent.
width() / 4 );
1714 double dy = std::fabs( currentExtent.
height() / 4 );
1748 if ( ! e->isAutoRepeat() )
1750 QApplication::setOverrideCursor( Qt::ClosedHandCursor );
1756 case Qt::Key_PageUp:
1761 case Qt::Key_PageDown:
1768 mUseParallelRendering = !mUseParallelRendering;
1773 mDrawRenderingStats = !mDrawRenderingStats;
1804 QApplication::restoreOverrideCursor();
1818 QgsDebugMsgLevel(
"Ignoring key release: " + QString::number( e->key() ), 2 );
1837 void QgsMapCanvas::beginZoomRect( QPoint pos )
1839 mZoomRect.setRect( 0, 0, 0, 0 );
1840 QApplication::setOverrideCursor( mZoomCursor );
1841 mZoomDragging =
true;
1843 QColor color( Qt::blue );
1844 color.setAlpha( 63 );
1845 mZoomRubberBand->setColor( color );
1846 mZoomRect.setTopLeft( pos );
1849 void QgsMapCanvas::endZoomRect( QPoint pos )
1851 mZoomDragging =
false;
1852 mZoomRubberBand.reset(
nullptr );
1853 QApplication::restoreOverrideCursor();
1856 mZoomRect.setRight( pos.x() );
1857 mZoomRect.setBottom( pos.y() );
1859 if ( mZoomRect.width() < 5 && mZoomRect.height() < 5 )
1866 mZoomRect = mZoomRect.normalized();
1869 const QSize &zoomRectSize = mZoomRect.size();
1870 const QSize &canvasSize = mSettings.
outputSize();
1871 double sfx =
static_cast< double >( zoomRectSize.width() ) / canvasSize.width();
1872 double sfy =
static_cast< double >( zoomRectSize.height() ) / canvasSize.height();
1873 double sf = std::max( sfx, sfy );
1884 if ( e->button() == Qt::MidButton )
1895 && e->modifiers() & Qt::ShiftModifier )
1897 beginZoomRect( e->pos() );
1903 showContextMenu( me.get() );
1926 if ( e->button() == Qt::MidButton )
1931 else if ( e->button() == Qt::BackButton )
1936 else if ( e->button() == Qt::ForwardButton )
1943 if ( mZoomDragging && e->button() == Qt::LeftButton )
1945 endZoomRect( e->pos() );
1955 QgsDebugMsgLevel( QStringLiteral(
"Right click in map tool zoom or pan, last tool is %1." ).arg(
1956 mLastNonZoomMapTool ? QStringLiteral(
"not null" ) : QStringLiteral(
"null" ) ), 2 );
1958 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCurrentLayer );
1961 if ( mLastNonZoomMapTool
1966 mLastNonZoomMapTool =
nullptr;
1986 QGraphicsView::resizeEvent( e );
1987 mResizeTimer->start( 500 );
1989 double oldScale = mSettings.
scale();
1990 QSize lastSize = viewport()->size();
1993 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
1999 double scaleFactor = oldScale / mSettings.
scale();
2017 QGraphicsView::paintEvent( e );
2022 if ( mBlockItemPositionUpdates )
2025 const QList<QGraphicsItem *> items = mScene->items();
2026 for ( QGraphicsItem *gi : items )
2043 QgsDebugMsgLevel(
"Wheel event delta " + QString::number( e->delta() ), 2 );
2048 if ( e->isAccepted() )
2052 if ( e->delta() == 0 )
2061 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( e->angleDelta().y() );
2063 if ( e->modifiers() & Qt::ControlModifier )
2066 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
2069 double signedWheelFactor = e->angleDelta().y() > 0 ? 1 / zoomFactor : zoomFactor;
2074 QgsPointXY newCenter( mousePos.
x() + ( ( oldCenter.
x() - mousePos.
x() ) * signedWheelFactor ),
2075 mousePos.
y() + ( ( oldCenter.
y() - mousePos.
y() ) * signedWheelFactor ) );
2083 mWheelZoomFactor = factor;
2112 ScaleRestorer restorer(
this );
2126 mScaleLocked = isLocked;
2137 else if ( mZoomDragging )
2139 mZoomRect.setBottomRight( e->pos() );
2140 mZoomRubberBand->setToCanvasRectangle( mZoomRect );
2141 mZoomRubberBand->show();
2154 if ( !panOperationInProgress() )
2171 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2181 mLastNonZoomMapTool = mMapTool;
2185 mLastNonZoomMapTool =
nullptr;
2195 connect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2203 if ( mMapTool && mMapTool == tool )
2205 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
2210 setCursor( Qt::ArrowCursor );
2213 if ( mLastNonZoomMapTool && mLastNonZoomMapTool == tool )
2215 mLastNonZoomMapTool =
nullptr;
2233 QBrush bgBrush( color );
2234 setBackgroundBrush( bgBrush );
2237 palette.setColor( backgroundRole(), color );
2238 setPalette( palette );
2242 mScene->setBackgroundBrush( bgBrush );
2251 return mScene->backgroundBrush().color();
2263 bool hasSelectedFeatures =
false;
2270 hasSelectedFeatures =
true;
2275 if ( hasSelectedFeatures )
2342 if ( mTheme ==
theme )
2356 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
2374 void QgsMapCanvas::connectNotify(
const char *signal )
2377 QgsDebugMsg(
"QgsMapCanvas connected to " + QString( signal ) );
2381 void QgsMapCanvas::layerRepaintRequested(
bool deferred )
2387 void QgsMapCanvas::autoRefreshTriggered()
2393 mRefreshAfterJob =
true;
2400 void QgsMapCanvas::updateAutoRefreshTimer()
2404 int minAutoRefreshInterval = -1;
2409 minAutoRefreshInterval = minAutoRefreshInterval > 0 ? std::min(
layer->
autoRefreshInterval(), minAutoRefreshInterval ) :
layer->autoRefreshInterval();
2412 if ( minAutoRefreshInterval > 0 )
2414 mAutoRefreshTimer.setInterval( minAutoRefreshInterval );
2415 mAutoRefreshTimer.start();
2419 mAutoRefreshTimer.stop();
2423 void QgsMapCanvas::projectThemesChanged()
2425 if ( mTheme.isEmpty() )
2456 double dx = end.
x() - start.
x();
2457 double dy = end.
y() - start.
y();
2459 c.set(
c.x() - dx,
c.y() - dy );
2492 setSceneRect( -pnt.x(), -pnt.y(), viewport()->size().width(), viewport()->size().height() );
2500 bool allHandled =
true;
2503 bool handled =
false;
2506 if ( handler && handler->customUriProviderKey() == uri.providerKey )
2508 if ( handler->handleCustomUriCanvasDrop( uri,
this ) )
2536 if ( !mPreviewEffect )
2541 mPreviewEffect->setEnabled( previewEnabled );
2546 if ( !mPreviewEffect )
2551 return mPreviewEffect->isEnabled();
2556 if ( !mPreviewEffect )
2561 mPreviewEffect->
setMode( mode );
2566 if ( !mPreviewEffect )
2571 return mPreviewEffect->
mode();
2576 if ( !mSnappingUtils )
2582 return mSnappingUtils;
2587 mSnappingUtils = utils;
2594 QDomNodeList nodes = doc.elementsByTagName( QStringLiteral(
"mapcanvas" ) );
2595 if ( nodes.count() )
2597 QDomNode node = nodes.item( 0 );
2600 if ( nodes.count() > 1 )
2602 for (
int i = 0; i < nodes.size(); ++i )
2604 QDomElement elementNode = nodes.at( i ).toElement();
2606 if ( elementNode.hasAttribute( QStringLiteral(
"name" ) ) && elementNode.attribute( QStringLiteral(
"name" ) ) == objectName() )
2608 node = nodes.at( i );
2616 if ( objectName() != QLatin1String(
"theMapCanvas" ) )
2627 QDomElement elem = node.toElement();
2628 if ( elem.hasAttribute( QStringLiteral(
"theme" ) ) )
2630 if (
QgsProject::instance()->mapThemeCollection()->hasMapTheme( elem.attribute( QStringLiteral(
"theme" ) ) ) )
2632 setTheme( elem.attribute( QStringLiteral(
"theme" ) ) );
2635 setAnnotationsVisible( elem.attribute( QStringLiteral(
"annotationsVisible" ), QStringLiteral(
"1" ) ).toInt() );
2638 const QDomNodeList scopeElements = elem.elementsByTagName( QStringLiteral(
"expressionContextScope" ) );
2639 if ( scopeElements.size() > 0 )
2641 const QDomElement scopeElement = scopeElements.at( 0 ).toElement();
2647 QgsDebugMsg( QStringLiteral(
"Couldn't read mapcanvas information from project" ) );
2660 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
2663 QgsDebugMsg( QStringLiteral(
"Unable to find qgis element in project file" ) );
2666 QDomNode qgisNode = nl.item( 0 );
2668 QDomElement mapcanvasNode = doc.createElement( QStringLiteral(
"mapcanvas" ) );
2669 mapcanvasNode.setAttribute( QStringLiteral(
"name" ), objectName() );
2670 if ( !mTheme.isEmpty() )
2671 mapcanvasNode.setAttribute( QStringLiteral(
"theme" ), mTheme );
2672 mapcanvasNode.setAttribute( QStringLiteral(
"annotationsVisible" ), mAnnotationsVisible );
2673 qgisNode.appendChild( mapcanvasNode );
2675 mSettings.
writeXml( mapcanvasNode, doc );
2678 QDomElement scopeElement = doc.createElement( QStringLiteral(
"expressionContextScope" ) );
2680 tmpScope.
removeVariable( QStringLiteral(
"atlas_featurenumber" ) );
2686 mapcanvasNode.appendChild( scopeElement );
2693 if ( mScaleLocked && !ignoreScaleLock )
2695 ScaleRestorer restorer(
this );
2730 bool allHandled =
true;
2733 bool handled =
false;
2736 if ( handler->canHandleCustomUriCanvasDrop( uri,
this ) )
2756 void QgsMapCanvas::mapToolDestroyed()
2764 if ( !QTouchDevice::devices().empty() )
2766 if ( e->type() == QEvent::Gesture )
2768 if ( QTapAndHoldGesture *tapAndHoldGesture = qobject_cast< QTapAndHoldGesture * >(
static_cast<QGestureEvent *
>( e )->gesture( Qt::TapAndHoldGesture ) ) )
2770 QPointF pos = tapAndHoldGesture->position();
2771 pos = mapFromGlobal( QPoint( pos.x(), pos.y() ) );
2779 return mMapTool->
gestureEvent(
static_cast<QGestureEvent *
>( e ) );
2785 return QGraphicsView::event( e );
2811 while ( mRefreshScheduled || mJob )
2813 QgsApplication::processEvents();
2829 QList<QgsMapCanvasAnnotationItem *> annotationItemList;
2830 const QList<QGraphicsItem *> items = mScene->items();
2831 for ( QGraphicsItem *gi : items )
2836 annotationItemList.push_back( aItem );
2840 return annotationItemList;
2845 mAnnotationsVisible = show;
2849 item->setVisible( show );
2863 void QgsMapCanvas::startPreviewJobs()
2872 schedulePreviewJob( 0 );
2875 void QgsMapCanvas::startPreviewJob(
int number )
2888 double dx = ( i - 1 ) * mapRect.
width();
2889 double dy = ( 1 - j ) * mapRect.
height();
2902 const QList<QgsMapLayer *>
layers = jobSettings.
layers();
2903 QList< QgsMapLayer * > previewLayers;
2912 QgsDebugMsgLevel( QStringLiteral(
"Layer %1 not rendered because it does not match the renderInPreview criterion %2" ).arg(
layer->
id() ).arg( mLastLayerRenderTime.value(
layer->
id() ) ), 3 );
2916 previewLayers <<
layer;
2921 job->setProperty(
"number", number );
2922 mPreviewJobs.append( job );
2927 void QgsMapCanvas::stopPreviewJobs()
2929 mPreviewTimer.stop();
2930 const auto previewJobs = mPreviewJobs;
2931 for (
auto previewJob : previewJobs )
2937 previewJob->cancelWithoutBlocking();
2940 mPreviewJobs.clear();
2943 void QgsMapCanvas::schedulePreviewJob(
int number )
2945 mPreviewTimer.setSingleShot(
true );
2946 mPreviewTimer.setInterval( PREVIEW_JOB_DELAY_MS );
2947 disconnect( mPreviewTimerConnection );
2948 mPreviewTimerConnection = connect( &mPreviewTimer, &QTimer::timeout,
this, [ = ]()
2950 startPreviewJob( number );
2952 mPreviewTimer.start();
2955 bool QgsMapCanvas::panOperationInProgress()
2960 if (
QgsMapToolPan *panTool = qobject_cast< QgsMapToolPan *>( mMapTool ) )
2962 if ( panTool->isDragging() )
2969 int QgsMapCanvas::nextZoomLevel(
const QList<double> &resolutions,
bool zoomIn )
const
2971 int resolutionLevel = -1;
2974 for (
int i = 0, n = resolutions.size(); i < n; ++i )
2976 if (
qgsDoubleNear( resolutions[i], currentResolution, 0.0001 ) )
2978 resolutionLevel =
zoomIn ? ( i - 1 ) : ( i + 1 );
2981 else if ( currentResolution <= resolutions[i] )
2983 resolutionLevel =
zoomIn ? ( i - 1 ) : i;
2987 return ( resolutionLevel < 0 || resolutionLevel >= resolutions.size() ) ? -1 : resolutionLevel;
2992 if ( !mZoomResolutions.isEmpty() )
2994 int zoomLevel = nextZoomLevel( mZoomResolutions,
true );
2995 if ( zoomLevel != -1 )
3000 return 1 / mWheelZoomFactor;
3005 if ( !mZoomResolutions.isEmpty() )
3007 int zoomLevel = nextZoomLevel( mZoomResolutions,
false );
3008 if ( zoomLevel != -1 )
3013 return mWheelZoomFactor;
SegmentationToleranceType
Segmentation tolerance as maximum angle or maximum difference between approximation and circle.
@ MaximumAngle
Maximum angle between generating radii (lines from arc center to output vertices)
virtual bool isEmpty() const
Returns true if the geometry is empty.
static QCursor getThemeCursor(Cursor cursor)
Helper to get a theme cursor.
static QgsImageCache * imageCache()
Returns the application's image cache, used for caching resampled versions of raster images.
static QgsSvgCache * svgCache()
Returns the application's SVG cache, used for caching SVG images and handling parameter replacement w...
static QgsCoordinateReferenceSystemRegistry * coordinateReferenceSystemRegistry()
Returns the application's coordinate reference system (CRS) registry, which handles known CRS definit...
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
void userCrsChanged(const QString &id)
Emitted whenever an existing user CRS definition is changed.
This class represents a coordinate reference system (CRS).
@ ShortString
A heavily abbreviated string, for use when a compact representation is required.
void updateDefinition()
Updates the definition and parameters of the coordinate reference system to their latest values.
QString userFriendlyIdentifier(IdentifierType type=MediumString) const
Returns a user friendly identifier for the CRS.
@ WKT_PREFERRED
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
Q_GADGET QgsUnitTypes::DistanceUnit mapUnits
Custom exception class for Coordinate Reference System related exceptions.
Abstract base class that may be implemented to handle new types of data to be dropped in QGIS.
Abstract base class for spatial data provider implementations.
virtual bool renderInPreview(const QgsDataProvider::PreviewContext &context)
Returns whether the layer must be rendered in preview jobs.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
double bearing(const QgsPointXY &p1, const QgsPointXY &p2) const
Computes the bearing (in radians) between two points.
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
QgsUnitTypes::DistanceUnit lengthUnits() const
Returns the units of distance for length calculations made by this object.
QgsRange which stores a range of double values.
Abstract interface for generating an expression context scope.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads scope variables from an XML element.
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes scope variables to an XML element.
bool removeVariable(const QString &name)
Removes a variable from the context scope, if found.
void setVariable(const QString &name, const QVariant &value, bool isStatic=false)
Convenience method for setting a variable in the context scope by name name and value.
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
static QgsExpressionContextScope * atlasScope(const QgsLayoutAtlas *atlas)
Creates a new scope which contains variables and functions relating to a QgsLayoutAtlas.
static QgsExpressionContextScope * mapSettingsScope(const QgsMapSettings &mapSettings)
Creates a new scope which contains variables and functions relating to a QgsMapSettings object.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setLimit(long limit)
Set the maximum number of features to request.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
bool hasGeometry() const
Returns true if the feature has an associated geometry.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
static QgsGeometry fromPointXY(const QgsPointXY &point) SIP_HOLDGIL
Creates a new geometry from a QgsPointXY object.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
void remoteImageFetched(const QString &url)
Emitted when the cache has finished retrieving an image file from a remote url.
Stores global configuration for labeling engine.
Class that stores computed placement from labeling engine.
static void warning(const QString &msg)
Goes to qWarning.
An interactive map canvas item which displays a QgsAnnotation.
An interface for objects which block interactions with a QgsMapCanvas.
Interaction
Available interactions to block.
An abstract class for items that can be placed on the map canvas.
virtual void updatePosition()
called on changed extent or resize event to update position of the item
Snapping utils instance that is connected to a canvas and updates the configuration (map settings + c...
Deprecated to be deleted, stuff from here should be moved elsewhere.
QPoint mouseLastXY
Last seen point of the mouse.
bool panSelectorDown
Flag to indicate the pan selector key is held down by user.
CanvasProperties()=default
Constructor for CanvasProperties.
QPoint rubberStartPoint
Beginning point of a rubber band.
bool mouseButtonDown
Flag to indicate status of mouse button.
Map canvas is a class for displaying all GIS data types on a canvas.
void setCurrentLayer(QgsMapLayer *layer)
void setCustomDropHandlers(const QVector< QPointer< QgsCustomDropHandler >> &handlers)
Sets a list of custom drop handlers to use when drop events occur on the canvas.
void contextMenuAboutToShow(QMenu *menu, QgsMapMouseEvent *event)
Emitted before the map canvas context menu will be shown.
QgsUnitTypes::DistanceUnit mapUnits() const
Convenience function for returning the current canvas map units.
void freeze(bool frozen=true)
Freeze/thaw the map canvas.
void enableAntiAliasing(bool flag)
used to determine if anti-aliasing is enabled or not
void setSnappingUtils(QgsSnappingUtils *utils)
Assign an instance of snapping utils to the map canvas.
bool isCachingEnabled() const
Check whether images of rendered layers are curerently being cached.
void zoomToFullExtent()
Zoom to the full extent of all layers.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the list of layers that should be shown in the canvas.
void setProject(QgsProject *project)
Sets the project linked to this canvas.
QColor selectionColor() const
Returns color for selected features.
bool event(QEvent *e) override
void setCachingEnabled(bool enabled)
Set whether to cache images of rendered layers.
void mouseReleaseEvent(QMouseEvent *e) override
QgsDoubleRange zRange() const
Returns the range of z-values which will be visible in the map.
void setExtent(const QgsRectangle &r, bool magnified=false)
Sets the extent of the map canvas to the specified rectangle.
void setRenderFlag(bool flag)
Sets whether a user has disabled canvas renders via the GUI.
QList< QgsMapCanvasAnnotationItem * > annotationItems() const
Returns a list of all annotation items in the canvas.
void updateCanvasItemPositions()
called on resize or changed extent to notify canvas items to change their rectangle
void extentsChanged()
Emitted when the extents of the map change.
void messageEmitted(const QString &title, const QString &message, Qgis::MessageLevel=Qgis::Info)
emit a message (usually to be displayed in a message bar)
void xyCoordinates(const QgsPointXY &p)
Emits current mouse position.
void stopRendering()
stop rendering (if there is any right now)
void magnificationChanged(double)
Emitted when the scale of the map changes.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets global labeling engine settings in the internal map settings.
QgsPointXY center() const
Gets map center, in geographical coordinates.
int layerCount() const
Returns number of layers on the map.
void setPreviewMode(QgsPreviewEffect::PreviewMode mode)
Sets a preview mode for the map canvas.
void layerStateChange()
This slot is connected to the visibility change of one or more layers.
QgsPreviewEffect::PreviewMode previewMode() const
Returns the current preview mode for the map canvas.
void zoomScale(double scale, bool ignoreScaleLock=false)
Zooms the canvas to a specific scale.
void zoomWithCenter(int x, int y, bool zoomIn)
Zooms in/out with a given center.
QPoint mouseLastXY()
returns last position of mouse cursor
void clearCache()
Make sure to remove any rendered images from cache (does nothing if cache is not enabled)
void renderComplete(QPainter *)
Emitted when the canvas has rendered.
void tapAndHoldGestureOccurred(const QgsPointXY &mapPoint, QTapAndHoldGesture *gesture)
Emitted whenever a tap and hold gesture occurs at the specified map point.
void zoomNextStatusChanged(bool)
Emitted when zoom next status changed.
const QgsDateTimeRange & temporalRange() const
Returns map canvas datetime range.
void setCanvasColor(const QColor &_newVal)
Write property of QColor bgColor.
QList< QgsMapLayer * > layers() const
Returns the list of layers shown within the map canvas.
void zoomByFactor(double scaleFactor, const QgsPointXY *center=nullptr, bool ignoreScaleLock=false)
Zoom with the factor supplied.
const QgsTemporalController * temporalController() const
Gets access to the temporal controller that will be used to update the canvas temporal range.
void flashGeometries(const QList< QgsGeometry > &geometries, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), const QColor &startColor=QColor(255, 0, 0, 255), const QColor &endColor=QColor(255, 0, 0, 0), int flashes=3, int duration=500)
Causes a set of geometries to flash within the canvas.
void setMapUpdateInterval(int timeMilliseconds)
Set how often map preview should be updated while it is being rendered (in milliseconds)
void rotationChanged(double)
Emitted when the rotation of the map changes.
void selectionChanged(QgsVectorLayer *layer)
Emitted when selection in any layer gets changed.
void dragEnterEvent(QDragEnterEvent *e) override
bool isDrawing()
Find out whether rendering is in progress.
void zRangeChanged()
Emitted when the map canvas z (elevation) range changes.
void keyPressEvent(QKeyEvent *e) override
void setZRange(const QgsDoubleRange &range)
Sets the range of z-values which will be visible in the map.
void clearExtentHistory()
Clears the list of extents and sets current extent as first item.
void zoomToPreviousExtent()
Zoom to the previous extent (view)
void enableMapTileRendering(bool flag)
sets map tile rendering flag
void panAction(QMouseEvent *event)
Called when mouse is moving and pan is activated.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the stored overrides of styles for rendering layers.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns global labeling engine settings from the internal map settings.
void mapToolSet(QgsMapTool *newTool, QgsMapTool *oldTool)
Emit map tool changed with the old tool.
void canvasColorChanged()
Emitted when canvas background color changes.
double zoomInFactor() const
Returns the zoom in factor.
void panToSelected(QgsVectorLayer *layer=nullptr)
Pan to the selected features of current (vector) layer keeping same extent.
void saveAsImage(const QString &fileName, QPixmap *QPixmap=nullptr, const QString &="PNG")
Save the contents of the map canvas to disk as an image.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
void setTemporalRange(const QgsDateTimeRange &range)
Set datetime range for the map canvas.
void moveCanvasContents(bool reset=false)
called when panning is in action, reset indicates end of panning
void zoomOut()
Zoom out with fixed factor.
void currentLayerChanged(QgsMapLayer *layer)
Emitted when the current layer is changed.
void setTemporalController(QgsTemporalController *controller)
Sets the temporal controller, tQgsMapCanvasInteractionBlockerhis controller will be used to update th...
void renderErrorOccurred(const QString &error, QgsMapLayer *layer)
Emitted whenever an error is encountered during a map render operation.
void waitWhileRendering()
Blocks until the rendering job has finished.
void mapRefreshCanceled()
Emitted when the pending map refresh has been canceled.
double magnificationFactor() const
Returns the magnification factor.
void writeProject(QDomDocument &)
called to write map canvas settings to project
void mousePressEvent(QMouseEvent *e) override
void updateScale()
Emits signal scaleChanged to update scale in main window.
void setMapSettingsFlags(QgsMapSettings::Flags flags)
Resets the flags for the canvas' map settings.
void setMagnificationFactor(double factor, const QgsPointXY *center=nullptr)
Sets the factor of magnification to apply to the map canvas.
void refreshAllLayers()
Reload all layers (including refreshing layer properties from their data sources),...
void unsetMapTool(QgsMapTool *mapTool)
Unset the current map tool or last non zoom tool.
void panActionEnd(QPoint releasePoint)
Ends pan action and redraws the canvas.
void resizeEvent(QResizeEvent *e) override
double zoomOutFactor() const
Returns the zoom in factor.
void renderStarting()
Emitted when the canvas is about to be rendered.
std::unique_ptr< CanvasProperties > mCanvasProperties
Handle pattern for implementation object.
void keyReleased(QKeyEvent *e)
Emit key release event.
const QgsLabelingResults * labelingResults() const
Gets access to the labeling results (may be nullptr)
void setWheelFactor(double factor)
Sets wheel zoom factor (should be greater than 1)
void setAnnotationsVisible(bool visible)
Sets whether annotations are visible in the canvas.
void layerStyleOverridesChanged()
Emitted when the configuration of overridden layer styles changes.
QgsMapCanvas(QWidget *parent=nullptr)
Constructor.
void panActionStart(QPoint releasePoint)
Starts a pan action.
void setPreviewJobsEnabled(bool enabled)
Sets whether canvas map preview jobs (low priority render jobs which render portions of the view just...
bool setReferencedExtent(const QgsReferencedRectangle &extent) SIP_THROW(QgsCsException)
Sets the canvas to the specified extent.
QgsRectangle fullExtent() const
Returns the combined extent for all layers on the map canvas.
void redrawAllLayers()
Clears all cached images and redraws all layers.
void keyReleaseEvent(QKeyEvent *e) override
bool isFrozen() const
Returns true if canvas is frozen.
void panToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids, bool alwaysRecenter=true)
Centers canvas extent to feature ids.
void scaleChanged(double)
Emitted when the scale of the map changes.
void mouseMoveEvent(QMouseEvent *e) override
void setCenter(const QgsPointXY ¢er)
Set the center of the map canvas, in geographical coordinates.
void setParallelRenderingEnabled(bool enabled)
Set whether the layers are rendered in parallel or sequentially.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
sets destination coordinate reference system
void flashFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids, const QColor &startColor=QColor(255, 0, 0, 255), const QColor &endColor=QColor(255, 0, 0, 0), int flashes=3, int duration=500)
Causes a set of features with matching ids from a vector layer to flash within the canvas.
void installInteractionBlocker(QgsMapCanvasInteractionBlocker *blocker)
Installs an interaction blocker onto the canvas, which may prevent certain map canvas interactions fr...
bool isParallelRenderingEnabled() const
Check whether the layers are rendered in parallel or sequentially.
void panDistanceBearingChanged(double distance, QgsUnitTypes::DistanceUnit unit, double bearing)
Emitted whenever the distance or bearing of an in-progress panning operation is changed.
double scale() const
Returns the last reported scale of the canvas.
QgsSnappingUtils * snappingUtils() const
Returns snapping utility class that is associated with map canvas.
double rotation() const
Gets the current map canvas rotation in clockwise degrees.
void temporalRangeChanged()
Emitted when the map canvas temporal range changes.
void paintEvent(QPaintEvent *e) override
QgsExpressionContextScope * defaultExpressionContextScope()
Creates a new scope which contains default variables and functions relating to the map canvas.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
void themeChanged(const QString &theme)
Emitted when the canvas has been assigned a different map theme.
void destinationCrsChanged()
Emitted when map CRS has changed.
void transformContextChanged()
Emitted when the canvas transform context is changed.
QgsMapTool * mapTool()
Returns the currently active tool.
void keyPressed(QKeyEvent *e)
Emit key press event.
void setMapTool(QgsMapTool *mapTool, bool clean=false)
Sets the map tool currently being used on the canvas.
QColor canvasColor() const
Read property of QColor bgColor.
void mapCanvasRefreshed()
Emitted when canvas finished a refresh request.
int mapUpdateInterval() const
Find out how often map preview should be updated while it is being rendered (in milliseconds)
void zoomLastStatusChanged(bool)
Emitted when zoom last status changed.
void setSelectionColor(const QColor &color)
Set color of selected vector features.
double mapUnitsPerPixel() const
Returns the mapUnitsPerPixel (map units per pixel) for the canvas.
void mouseDoubleClickEvent(QMouseEvent *e) override
void selectionChangedSlot()
Receives signal about selection change, and pass it on with layer info.
void zoomToNextExtent()
Zoom to the next extent (view)
void layersChanged()
Emitted when a new set of layers has been received.
void zoomToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids)
Set canvas extent to the bounding box of a set of features.
void zoomIn()
Zoom in with fixed factor.
QgsMapLayer * layer(int index)
Returns the map layer at position index in the layer stack.
bool allowInteraction(QgsMapCanvasInteractionBlocker::Interaction interaction) const
Returns true if the specified interaction is currently permitted on the canvas.
void wheelEvent(QWheelEvent *e) override
bool previewModeEnabled() const
Returns whether a preview mode is enabled for the map canvas.
const QgsMapToPixel * getCoordinateTransform()
Gets the current coordinate transform.
void dropEvent(QDropEvent *event) override
void setPreviewModeEnabled(bool previewEnabled)
Enables a preview mode for the map canvas.
QgsProject * project()
Returns the project linked to this canvas.
void setScaleLocked(bool isLocked)
Lock the scale, so zooming can be performed using magnication.
void setRotation(double degrees)
Set the rotation of the map canvas in clockwise degrees.
void zoomToSelected(QgsVectorLayer *layer=nullptr)
Zoom to the extent of the selected features of provided (vector) layer.
void removeInteractionBlocker(QgsMapCanvasInteractionBlocker *blocker)
Removes an interaction blocker from the canvas.
void readProject(const QDomDocument &)
called to read map canvas settings from project
void setTheme(const QString &theme)
Sets a map theme to show in the canvas.
void zoomToFeatureExtent(QgsRectangle &rect)
Zooms to feature extent.
QMap< QString, QString > layerStyleOverrides() const
Returns the stored overrides of styles for layers.
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
QgsRectangle extent() const
Returns the current zoom extent of the map canvas.
void refresh()
Repaints the canvas map.
QgsMapLayer * currentLayer()
returns current layer (set by legend widget)
virtual QgsMapLayerElevationProperties::Flags flags() const
Returns flags associated to the elevation properties.
@ FlagDontInvalidateCachedRendersWhenRangeChanges
Any cached rendering will not be invalidated when z range context is modified.
virtual bool hasElevation() const
Returns true if the layer has an elevation or z component.
Base class for all map layer types.
virtual bool isSpatial() const
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
void autoRefreshIntervalChanged(int interval)
Emitted when the auto refresh interval changes.
QgsCoordinateReferenceSystem crs
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
bool hasAutoRefreshEnabled() const
Returns true if auto refresh is enabled for the layer.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
virtual QgsMapLayerElevationProperties * elevationProperties()
Returns the layer's elevation properties.
virtual Q_INVOKABLE QgsDataProvider * dataProvider()
Returns the layer's data provider, it may be nullptr.
virtual Q_INVOKABLE void reload()
Synchronises with changes in the datasource.
virtual QgsMapLayerTemporalProperties * temporalProperties()
Returns the layer's temporal properties.
A QgsMapMouseEvent is the result of a user interaction with the mouse on a QgsMapCanvas.
This class is responsible for keeping cache of rendered images resulting from a map rendering job.
void clear()
Invalidates the cache contents, clearing all cached images.
void invalidateCacheForLayer(QgsMapLayer *layer)
Invalidates cached images which relate to the specified map layer.
Job implementation that renders everything sequentially using a custom painter.
void waitForFinished() override
Block until the job has finished.
void start() override
Start the rendering job and immediately return.
virtual void waitForFinished()=0
Block until the job has finished.
void setCache(QgsMapRendererCache *cache)
Assign a cache to be used for reading and storing rendered images of individual layers.
virtual QgsLabelingResults * takeLabelingResults()=0
Gets pointer to internal labeling engine (in order to get access to the results).
QHash< QgsMapLayer *, int > perLayerRenderingTime() const
Returns the render time (in ms) per layer.
virtual bool usedCachedLabels() const =0
Returns true if the render job was able to use a cached labeling solution.
Errors errors() const
List of errors that happened during the rendering job - available when the rendering has been finishe...
const QgsMapSettings & mapSettings() const
Returns map settings with which this job was started.
void finished()
emitted when asynchronous rendering is finished (or canceled).
int renderingTime() const
Returns the total time it took to finish the job (in milliseconds).
virtual void start()=0
Start the rendering job and immediately return.
virtual bool isActive() const =0
Tell whether the rendering job is currently running in background.
void setLayerRenderingTimeHints(const QHash< QString, int > &hints)
Sets approximate render times (in ms) for map layers.
virtual void cancelWithoutBlocking()=0
Triggers cancellation of the rendering job without blocking.
Job implementation that renders all layers in parallel.
Intermediate base class adding functionality that allows client to query the rendered image.
virtual QImage renderedImage()=0
Gets a preview/resulting image.
Job implementation that renders everything sequentially in one thread.
static QString worldFileContent(const QgsMapSettings &mapSettings)
Creates the content of a world file.
The QgsMapSettings class contains configuration for rendering of the map.
void writeXml(QDomNode &node, QDomDocument &doc)
QgsPointXY layerToMapCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from layer's CRS to output CRS
void setSelectionColor(const QColor &color)
Sets the color that is used for drawing of selected vector features.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the list of layers to render in the map.
double scale() const
Returns the calculated map scale.
QgsRectangle layerExtentToOutputExtent(const QgsMapLayer *layer, QgsRectangle extent) const
transform bounding box from layer's CRS to output CRS
QgsDoubleRange zRange() const
Returns the range of z-values which will be visible in the map.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
bool testFlag(Flag flag) const
Check whether a particular flag is enabled.
@ RenderPartialOutput
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
@ UseRenderingOptimization
Enable vector simplification and other rendering optimizations.
@ Antialiasing
Enable anti-aliasing for map rendering.
@ DrawEditingInfo
Enable drawing of vertex markers for layers in editing mode.
@ RenderPreviewJob
Render is a 'canvas preview' render, and shortcuts should be taken to ensure fast rendering.
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
@ DrawLabeling
Enable drawing of labels on top of the map.
double magnificationFactor() const
Returns the magnification factor.
void setDevicePixelRatio(float dpr)
Sets the device pixel ratio.
void setZRange(const QgsDoubleRange &range)
Sets the range of z-values which will be visible in the map.
QColor backgroundColor() const
Returns the background color of the map.
double mapUnitsPerPixel() const
Returns the distance in geographical coordinates that equals to one pixel in the map.
float devicePixelRatio() const
Returns the device pixel ratio.
QSize outputSize() const
Returns the size of the resulting map image, in pixels.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the map of map layer style overrides (key: layer ID, value: style name) where a different style ...
void setExtent(const QgsRectangle &rect, bool magnified=true)
Sets the coordinates of the rectangle which should be rendered.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
QgsUnitTypes::DistanceUnit mapUnits() const
Returns the units of the map's geographical coordinates - used for scale calculation.
const QgsMapToPixel & mapToPixel() const
QColor selectionColor() const
Returns the color that is used for drawing of selected vector features.
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes takes output image size into accou...
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets the global configuration of the labeling engine.
QgsRectangle fullExtent() const
returns current extent of layer set
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the coordinate transform context, which stores various information regarding which datum transfo...
void setRotation(double rotation)
Sets the rotation of the resulting map image, in degrees clockwise.
QList< QgsMapLayer * > layers() const
Returns the list of layers which will be rendered in the map.
void setPathResolver(const QgsPathResolver &resolver)
Sets the path resolver for conversion between relative and absolute paths during rendering operations...
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
QMap< QString, QString > layerStyleOverrides() const
Returns the map of map layer style overrides (key: layer ID, value: style name) where a different sty...
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
bool hasValidSettings() const
Check whether the map settings are valid and can be used for rendering.
void setFlag(Flag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected)
void setOutputSize(QSize size)
Sets the size of the resulting map image, in pixels.
void setFlags(QgsMapSettings::Flags flags)
Sets combination of flags that will be used for rendering.
QgsPointXY mapToLayerCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from output CRS to layer's CRS
void setBackgroundColor(const QColor &color)
Sets the background color of the map.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Sets the destination crs (coordinate reference system) for the map render.
void readXml(QDomNode &node)
void setMagnificationFactor(double factor, const QgsPointXY *center=nullptr)
Set the magnification factor.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
void mapThemesChanged()
Emitted when map themes within the collection are changed.
void mapThemeRenamed(const QString &name, const QString &newName)
Emitted when a map theme within the collection is renamed.
bool hasMapTheme(const QString &name) const
Returns whether a map theme with a matching name exists.
void mapThemeChanged(const QString &theme)
Emitted when a map theme changes definition.
Perform transforms between map coordinates and device coordinates.
double mapUnitsPerPixel() const
Returns current map units per pixel.
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
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).
static bool isUriList(const QMimeData *data)
QList< QgsMimeDataUtils::Uri > UriList
static UriList decodeUriList(const QMimeData *data)
A class to represent a 2D point.
double sqrDist(double x, double y) const SIP_HOLDGIL
Returns the squared distance between this point a specified x, y coordinate.
A graphics effect which can be applied to a widget to simulate various printing and color blindness m...
void setMode(PreviewMode mode)
Sets the mode for the preview effect, which controls how the effect modifies a widgets appearance.
PreviewMode mode() const
Returns the mode used for the preview effect.
QgsReferencedRectangle defaultViewExtent() const
Returns the default view extent, which should be used as the initial map extent when this project is ...
QgsReferencedRectangle fullExtent() const
Returns the full extent of the project, which represents the maximal limits of the project.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
static QgsProject * instance()
Returns the QgsProject singleton instance.
Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
QgsMapThemeCollection * mapThemeCollection
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
QgsCoordinateTransformContext transformContext
void readProject(const QDomDocument &)
Emitted when a project is being read.
void writeProject(QDomDocument &)
Emitted when the project is being written.
const QgsProjectViewSettings * viewSettings() const
Returns the project's view settings, which contains settings and properties relating to how a QgsProj...
void transformContextChanged()
Emitted when the project transformContext() is changed.
A generic dialog to prompt the user for a Coordinate Reference System.
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
void setYMinimum(double y) SIP_HOLDGIL
Set the minimum y value.
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
void setXMaximum(double x) SIP_HOLDGIL
Set the maximum x value.
void setXMinimum(double x) SIP_HOLDGIL
Set the minimum x value.
double height() const SIP_HOLDGIL
Returns the height of the rectangle.
void setYMaximum(double y) SIP_HOLDGIL
Set the maximum y value.
void setMinimal() SIP_HOLDGIL
Set a rectangle so that min corner is at max and max corner is at min.
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
bool isEmpty() const
Returns true if the rectangle is empty.
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
A QgsRectangle with associated coordinate reference system.
A class for drawing transient features (e.g.
void setWidth(int width)
Sets the width of the line.
void setSecondaryStrokeColor(const QColor &color)
Sets a secondary stroke color for the rubberband which will be drawn under the main stroke color.
@ ICON_CIRCLE
A circle is used to highlight points (○)
void setStrokeColor(const QColor &color)
Sets the stroke color for the rubberband.
QColor secondaryStrokeColor
void setIcon(IconType icon)
Sets the icon type to highlight point geometries.
void addGeometry(const QgsGeometry &geometry, QgsVectorLayer *layer, bool doUpdate=true)
Adds the geometry of an existing feature to a rubberband This is useful for multi feature highlightin...
void updatePosition() override
called on changed extent or resize event to update position of the item
void setFillColor(const QColor &color)
Sets the fill color for the rubberband.
Scoped object for saving and restoring a QPainter object's state.
Scoped object for logging of the runtime for a single operation or group of operations.
This class is a composition of two QSettings instances:
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
T enumValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on an enum.
This class has all the configuration of snapping and can return answers to snapping queries.
void remoteSvgFetched(const QString &url)
Emitted when the cache has finished retrieving an SVG file from a remote url.
A controller base class for temporal objects, contains a signal for notifying updates of the objects ...
void updateTemporalRange(const QgsDateTimeRange &range)
Signals that a temporal range has changed and needs to be updated in all connected objects.
bool isActive() const
Returns true if the temporal property is active.
virtual QgsTemporalProperty::Flags flags() const
Returns flags associated to the temporal property.
@ FlagDontInvalidateCachedRendersWhenRangeChanges
Any cached rendering will not be invalidated when temporal range context is modified.
const QgsDateTimeRange & temporalRange() const
Returns the datetime range for the object.
void setIsTemporal(bool enabled)
Sets whether the temporal range is enabled (i.e.
void setTemporalRange(const QgsDateTimeRange &range)
Sets the temporal range for the object.
Temporarily sets a cursor override for the QApplication for the lifetime of the object.
void release()
Releases the cursor override early (i.e.
DistanceUnit
Units of distance.
@ DistanceDegrees
Degrees, for planar geographic CRS distance measurements.
Represents a vector layer which manages a vector based data sets.
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
A class to represent a vector.
static GeometryType geometryType(Type type) SIP_HOLDGIL
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
constexpr double CANVAS_MAGNIFICATION_MIN
Minimum magnification level allowed in map canvases.
constexpr double CANVAS_MAGNIFICATION_MAX
Maximum magnification level allowed in map canvases.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
QSet< QgsFeatureId > QgsFeatureIds
#define QgsDebugMsgLevel(str, level)
const QgsCoordinateReferenceSystem & crs
Stores settings related to the context in which a preview job runs.
double maxRenderingTimeMs
Default maximum allowable render time, in ms.
double lastRenderingTimeMs
Previous rendering time for the layer, in ms.