20 #include <QApplication> 24 #include <QGraphicsItem> 25 #include <QGraphicsScene> 26 #include <QGraphicsView> 28 #include <QMouseEvent> 30 #include <QPaintEvent> 33 #include <QTextStream> 34 #include <QResizeEvent> 36 #include <QStringList> 37 #include <QWheelEvent> 102 : QGraphicsView( parent )
104 , mExpressionContextScope( tr(
"Map Canvas" ) )
106 mScene =
new QGraphicsScene();
108 setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
109 setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
110 setMouseTracking(
true );
111 setFocusPolicy( Qt::StrongFocus );
113 mResizeTimer =
new QTimer(
this );
114 mResizeTimer->setSingleShot(
true );
117 mRefreshTimer =
new QTimer(
this );
118 mRefreshTimer->setSingleShot(
true );
119 connect( mRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::refreshMap );
122 mMap =
new QgsMapCanvasMap(
this );
157 double segmentationTolerance = settings.
value( QStringLiteral(
"qgis/segmentationTolerance" ),
"0.01745" ).toDouble();
162 mWheelZoomFactor = settings.
value( QStringLiteral(
"qgis/zoom_factor" ), 2 ).toDouble();
164 QSize s = viewport()->size();
166 setSceneRect( 0, 0, s.width(), s.height() );
167 mScene->setSceneRect( QRectF( 0, 0, s.width(), s.height() ) );
171 connect( &mMapUpdateTimer, &QTimer::timeout,
this, &QgsMapCanvas::mapUpdateTimeout );
172 mMapUpdateTimer.setInterval( 250 );
177 grabGesture( Qt::PinchGesture );
178 viewport()->setAttribute( Qt::WA_AcceptTouchEvents );
182 viewport()->setGraphicsEffect( mPreviewEffect );
186 connect( &mAutoRefreshTimer, &QTimer::timeout,
this, &QgsMapCanvas::autoRefreshTriggered );
190 setInteractive(
false );
208 mLastNonZoomMapTool =
nullptr;
218 QList< QgsMapRendererQImageJob * >::const_iterator previewJob = mPreviewJobs.constBegin();
219 for ( ; previewJob != mPreviewJobs.constEnd(); ++previewJob )
231 QList<QGraphicsItem *> list = mScene->items();
232 QList<QGraphicsItem *>::iterator it = list.begin();
233 while ( it != list.end() )
235 QGraphicsItem *item = *it;
240 mScene->deleteLater();
247 delete mLabelingResults;
256 factor = qBound( magnifierMin, factor, magnifierMax );
285 if ( index >= 0 && index < (
int ) layers.size() )
286 return layers[index];
293 mCurrentLayer =
layer;
304 return nullptr != mJob;
317 if ( !mTheme.isEmpty() )
320 setLayersPrivate( layers );
323 void QgsMapCanvas::setLayersPrivate(
const QList<QgsMapLayer *> &
layers )
325 QList<QgsMapLayer *> oldLayers = mSettings.
layers();
328 if ( layers == oldLayers )
335 if (
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer ) )
349 if (
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer ) )
358 updateAutoRefreshTimer();
380 rect = transform.transformBoundingBox( mSettings.
visibleExtent() );
385 QgsDebugMsg( QString(
"Transform error caught: %1" ).arg( e.
what() ) );
397 QgsDebugMsg(
"refreshing after destination CRS changed" );
412 return mLabelingResults;
439 return nullptr != mCache;
450 mUseParallelRendering = enabled;
455 return mUseParallelRendering;
460 mMapUpdateTimer.setInterval( timeMilliseconds );
465 return mMapUpdateTimer.interval();
471 return mCurrentLayer;
479 QgsDebugMsg(
"CANVAS refresh - invalid settings -> nothing to do" );
483 if ( !mRenderFlag || mFrozen )
489 if ( mRefreshScheduled )
495 mRefreshScheduled =
true;
500 mRefreshTimer->start( 1 );
503 void QgsMapCanvas::refreshMap()
505 Q_ASSERT( mRefreshScheduled );
523 if ( !mTheme.isEmpty() )
536 mJobCanceled =
false;
537 if ( mUseParallelRendering )
552 mRefreshScheduled =
false;
554 mMapUpdateTimer.start();
559 void QgsMapCanvas::mapThemeChanged(
const QString &
theme )
561 if ( theme == mTheme )
566 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
580 void QgsMapCanvas::rendererJobFinished()
582 QgsDebugMsg( QString(
"CANVAS finish! %1" ).arg( !mJobCanceled ) );
584 mMapUpdateTimer.stop();
598 delete mLabelingResults;
609 if ( settings.
value( QStringLiteral(
"Map/logCanvasRefreshEvent" ),
false ).toBool() )
611 QString logMsg = tr(
"Canvas refresh: %1 ms" ).arg( mJob->
renderingTime() );
615 if ( mDrawRenderingStats )
617 int w = img.width(), h = img.height();
618 QFont fnt = p.font();
621 int lh = p.fontMetrics().height() * 2;
622 QRect r( 0, h - lh, w, lh );
623 p.setPen( Qt::NoPen );
624 p.setBrush( QColor( 0, 0, 0, 110 ) );
626 p.setPen( Qt::white );
627 QString msg = QStringLiteral(
"%1 :: %2 ms" ).arg( mUseParallelRendering ?
"PARALLEL" :
"SEQUENTIAL" ).arg( mJob->
renderingTime() );
628 p.drawText( r, msg, QTextOption( Qt::AlignCenter ) );
633 mMap->setContent( img, imageRect( img, mSettings ) );
635 mLastLayerRenderTime.clear();
637 for (
auto it = times.constBegin(); it != times.constEnd(); ++it )
639 mLastLayerRenderTime.insert( it.key()->id(), it.value() );
641 if ( mUsePreviewJobs )
653 void QgsMapCanvas::previewJobFinished()
661 mPreviewJobs.removeAll( job );
663 int number = job->property(
"number" ).toInt();
666 startPreviewJob( number + 1 );
680 QgsRectangle rect( topLeft.
x(), topLeft.
y(), topLeft.
x() + img.width()*res, topLeft.
y() - img.height()*res );
686 return mUsePreviewJobs;
691 mUsePreviewJobs = enabled;
694 void QgsMapCanvas::mapUpdateTimeout()
699 mMap->setContent( img, imageRect( img, mSettings ) );
728 image = theQPixmap->toImage();
729 painter.begin( &image );
739 image = mMap->contentImage().copy();
740 painter.begin( &image );
744 QStyleOptionGraphicsItem option;
745 option.initFrom(
this );
746 QGraphicsItem *item =
nullptr;
747 QListIterator<QGraphicsItem *> i( items() );
749 while ( i.hasPrevious() )
753 if ( !item || dynamic_cast< QgsMapCanvasAnnotationItem * >( item ) )
760 QPointF itemScenePos = item->scenePos();
761 painter.translate( itemScenePos.x(), itemScenePos.y() );
763 item->paint( &painter, &option );
769 image.save( fileName, format.toLocal8Bit().data() );
771 QFileInfo myInfo = QFileInfo( fileName );
774 QString outputSuffix = myInfo.suffix();
775 QString myWorldFileName = myInfo.absolutePath() +
'/' + myInfo.baseName() +
'.' 776 + outputSuffix.at( 0 ) + outputSuffix.at( myInfo.suffix().size() - 1 ) +
'w';
777 QFile myWorldFile( myWorldFileName );
778 if ( !myWorldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
782 QTextStream myStream( &myWorldFile );
803 if ( ( r == current ) && magnified )
816 QgsDebugMsg(
"Empty extent - keeping old scale with new center!" );
825 if ( mLastExtent.size() > 20 )
826 mLastExtent.removeAt( 0 );
829 for (
int i = mLastExtent.size() - 1; i > mLastExtentIndex; i-- )
831 mLastExtent.removeAt( i );
834 mLastExtent.append(
extent() );
837 if ( mLastExtent.size() > 20 )
839 mLastExtent.removeAt( 0 );
843 mLastExtentIndex = mLastExtent.size() - 1;
853 double x = center.
x();
854 double y = center.
y();
880 if ( degrees == current )
902 extent.
scale( 1.05 );
913 if ( mLastExtentIndex > 0 )
916 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
929 if ( mLastExtentIndex < mLastExtent.size() - 1 )
932 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
945 mLastExtent.append(
extent() ) ;
946 mLastExtentIndex = mLastExtent.size() - 1;
983 rect.
scale( 1.0, &c );
1007 if ( boundingBoxOfFeatureIds( ids, layer, bbox, errorMsg ) )
1027 if ( boundingBoxOfFeatureIds( ids, layer, bbox, errorMsg ) )
1043 int featureCount = 0;
1051 errorMsg = tr(
"Feature does not have a geometry" );
1055 errorMsg = tr(
"Feature geometry is empty" );
1057 if ( !errorMsg.isEmpty() )
1066 if ( featureCount != ids.count() )
1068 errorMsg = tr(
"Feature not found" );
1099 const QColor &color1,
const QColor &color2,
1100 int flashes,
int duration )
1107 QList< QgsGeometry > geoms;
1123 if ( geometries.isEmpty() )
1129 rb->addGeometry( geom, crs );
1134 rb->setSecondaryStrokeColor( QColor( 255, 255, 255 ) );
1139 QColor startColor = color1;
1140 if ( !startColor.isValid() )
1144 startColor = rb->fillColor();
1148 startColor = rb->strokeColor();
1150 startColor.setAlpha( 255 );
1152 QColor endColor = color2;
1153 if ( !endColor.isValid() )
1155 endColor = startColor;
1156 endColor.setAlpha( 0 );
1160 QVariantAnimation *animation =
new QVariantAnimation(
this );
1161 connect( animation, &QVariantAnimation::finished,
this, [animation, rb]
1163 animation->deleteLater();
1166 connect( animation, &QPropertyAnimation::valueChanged,
this, [rb, geomType](
const QVariant & value )
1168 QColor c = value.value<QColor>();
1171 rb->setFillColor( c );
1175 rb->setStrokeColor( c );
1176 QColor c = rb->secondaryStrokeColor();
1177 c.setAlpha( c.alpha() );
1178 rb->setSecondaryStrokeColor( c );
1183 animation->setDuration( duration * flashes );
1184 animation->setStartValue( endColor );
1185 double midStep = 0.2 / flashes;
1186 for (
int i = 0; i < flashes; ++i )
1188 double start =
static_cast< double >( i ) / flashes;
1189 animation->setKeyValueAt( start + midStep, startColor );
1190 double end =
static_cast< double >( i + 1 ) / flashes;
1192 animation->setKeyValueAt( end, endColor );
1194 animation->setEndValue( endColor );
1211 double dx = std::fabs( currentExtent.
width() / 4 );
1212 double dy = std::fabs( currentExtent.
height() / 4 );
1246 if ( ! e->isAutoRepeat() )
1248 QApplication::setOverrideCursor( Qt::ClosedHandCursor );
1254 case Qt::Key_PageUp:
1259 case Qt::Key_PageDown:
1266 mUseParallelRendering = !mUseParallelRendering;
1271 mDrawRenderingStats = !mDrawRenderingStats;
1284 QgsDebugMsg(
"Ignoring key: " + QString::number( e->key() ) );
1302 QApplication::restoreOverrideCursor();
1316 QgsDebugMsg(
"Ignoring key release: " + QString::number( e->key() ) );
1335 void QgsMapCanvas::beginZoomRect( QPoint pos )
1337 mZoomRect.setRect( 0, 0, 0, 0 );
1338 QApplication::setOverrideCursor( mZoomCursor );
1339 mZoomDragging =
true;
1341 QColor color( Qt::blue );
1342 color.setAlpha( 63 );
1343 mZoomRubberBand->setColor( color );
1344 mZoomRect.setTopLeft( pos );
1347 void QgsMapCanvas::endZoomRect( QPoint pos )
1349 mZoomDragging =
false;
1350 mZoomRubberBand.reset(
nullptr );
1351 QApplication::restoreOverrideCursor();
1354 mZoomRect.setRight( pos.x() );
1355 mZoomRect.setBottom( pos.y() );
1357 if ( mZoomRect.width() < 5 && mZoomRect.height() < 5 )
1364 mZoomRect = mZoomRect.normalized();
1367 const QSize &zoomRectSize = mZoomRect.size();
1368 const QSize &canvasSize = mSettings.
outputSize();
1369 double sfx = ( double )zoomRectSize.width() / canvasSize.width();
1370 double sfy = ( double )zoomRectSize.height() / canvasSize.height();
1371 double sf = std::max( sfx, sfy );
1382 if ( e->button() == Qt::MidButton )
1393 && e->modifiers() & Qt::ShiftModifier )
1395 beginZoomRect( e->pos() );
1420 if ( e->button() == Qt::MidButton )
1425 else if ( e->button() == Qt::BackButton )
1430 else if ( e->button() == Qt::ForwardButton )
1437 if ( mZoomDragging && e->button() == Qt::LeftButton )
1439 endZoomRect( e->pos() );
1449 QgsDebugMsg(
"Right click in map tool zoom or pan, last tool is " +
1450 QString( mLastNonZoomMapTool ?
"not null." :
"null." ) );
1455 if ( mLastNonZoomMapTool
1460 mLastNonZoomMapTool =
nullptr;
1480 QGraphicsView::resizeEvent( e );
1481 mResizeTimer->start( 500 );
1483 QSize lastSize = viewport()->size();
1487 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
1502 QGraphicsView::paintEvent( e );
1507 QList<QGraphicsItem *> list = mScene->items();
1508 QList<QGraphicsItem *>::iterator it = list.begin();
1509 while ( it != list.end() )
1528 QgsDebugMsg(
"Wheel event delta " + QString::number( e->delta() ) );
1533 if ( e->isAccepted() )
1537 double zoomFactor = mWheelZoomFactor;
1540 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( e->angleDelta().y() );
1542 if ( e->modifiers() & Qt::ControlModifier )
1545 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
1548 double signedWheelFactor = e->angleDelta().y() > 0 ? 1 / zoomFactor : zoomFactor;
1553 QgsPointXY newCenter( mousePos.
x() + ( ( oldCenter.
x() - mousePos.
x() ) * signedWheelFactor ),
1554 mousePos.
y() + ( ( oldCenter.
y() - mousePos.
y() ) * signedWheelFactor ) );
1562 mWheelZoomFactor = factor;
1584 double scaleFactor = ( zoomIn ? 1 / mWheelZoomFactor : mWheelZoomFactor );
1595 r.
scale( scaleFactor, ¢er );
1603 mScaleLocked = isLocked;
1614 else if ( mZoomDragging )
1616 mZoomRect.setBottomRight( e->pos() );
1617 mZoomRubberBand->setToCanvasRectangle( mZoomRect );
1618 mZoomRubberBand->show();
1631 QPoint xy = e->pos();
1646 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
1656 mLastNonZoomMapTool = mMapTool;
1660 mLastNonZoomMapTool =
nullptr;
1669 connect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
1678 if ( mMapTool && mMapTool == tool )
1683 setCursor( Qt::ArrowCursor );
1686 if ( mLastNonZoomMapTool && mLastNonZoomMapTool == tool )
1688 mLastNonZoomMapTool =
nullptr;
1701 QBrush bgBrush( color );
1702 setBackgroundBrush( bgBrush );
1705 palette.setColor( backgroundRole(), color );
1706 setPalette( palette );
1710 mScene->setBackgroundBrush( bgBrush );
1717 return mScene->backgroundBrush().color();
1784 if ( mTheme == theme )
1798 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
1816 void QgsMapCanvas::connectNotify(
const char *signal )
1819 QgsDebugMsg(
"QgsMapCanvas connected to " + QString( signal ) );
1823 void QgsMapCanvas::layerRepaintRequested(
bool deferred )
1829 void QgsMapCanvas::autoRefreshTriggered()
1842 void QgsMapCanvas::updateAutoRefreshTimer()
1846 int minAutoRefreshInterval = -1;
1853 if ( minAutoRefreshInterval > 0 )
1855 mAutoRefreshTimer.setInterval( minAutoRefreshInterval );
1856 mAutoRefreshTimer.start();
1860 mAutoRefreshTimer.stop();
1864 void QgsMapCanvas::projectThemesChanged()
1866 if ( mTheme.isEmpty() )
1892 double dx = end.
x() - start.
x();
1893 double dy = end.
y() - start.
y();
1895 c.
set( c.
x() - dx, c.
y() - dy );
1915 setSceneRect( -pnt.x(), -pnt.y(), viewport()->size().width(), viewport()->size().height() );
1925 if ( !mPreviewEffect )
1930 mPreviewEffect->setEnabled( previewEnabled );
1935 if ( !mPreviewEffect )
1940 return mPreviewEffect->isEnabled();
1945 if ( !mPreviewEffect )
1950 mPreviewEffect->
setMode( mode );
1955 if ( !mPreviewEffect )
1960 return mPreviewEffect->
mode();
1965 if ( !mSnappingUtils )
1971 return mSnappingUtils;
1976 mSnappingUtils = utils;
1981 QDomNodeList nodes = doc.elementsByTagName( QStringLiteral(
"mapcanvas" ) );
1982 if ( nodes.count() )
1984 QDomNode node = nodes.item( 0 );
1987 if ( nodes.count() > 1 )
1989 for (
int i = 0; i < nodes.size(); ++i )
1991 QDomElement elementNode = nodes.at( i ).toElement();
1993 if ( elementNode.hasAttribute( QStringLiteral(
"name" ) ) && elementNode.attribute( QStringLiteral(
"name" ) ) == objectName() )
1995 node = nodes.at( i );
2003 if ( objectName() != QStringLiteral(
"theMapCanvas" ) )
2014 QDomElement elem = node.toElement();
2015 if ( elem.hasAttribute( QStringLiteral(
"theme" ) ) )
2019 setTheme( elem.attribute( QStringLiteral(
"theme" ) ) );
2022 setAnnotationsVisible( elem.attribute( QStringLiteral(
"annotationsVisible" ), QStringLiteral(
"1" ) ).toInt() );
2026 QgsDebugMsg(
"Couldn't read mapcanvas information from project" );
2034 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
2037 QgsDebugMsg(
"Unable to find qgis element in project file" );
2040 QDomNode qgisNode = nl.item( 0 );
2042 QDomElement mapcanvasNode = doc.createElement( QStringLiteral(
"mapcanvas" ) );
2043 mapcanvasNode.setAttribute( QStringLiteral(
"name" ), objectName() );
2044 if ( !mTheme.isEmpty() )
2045 mapcanvasNode.setAttribute( QStringLiteral(
"theme" ), mTheme );
2046 mapcanvasNode.setAttribute( QStringLiteral(
"annotationsVisible" ), mAnnotationsVisible );
2047 qgisNode.appendChild( mapcanvasNode );
2049 mSettings.
writeXml( mapcanvasNode, doc );
2061 QString settingsString =
"/Projections/" + source.
authid() +
"//" + destination.
authid();
2062 QVariant defaultSrcTransform = s.
value( settingsString +
"_srcTransform" );
2063 QVariant defaultDestTransform = s.
value( settingsString +
"_destTransform" );
2064 if ( defaultSrcTransform.isValid() && defaultDestTransform.isValid() )
2066 int sourceDatumTransform = defaultSrcTransform.toInt();
2067 int destinationDatumTransform = defaultDestTransform.toInt();
2075 if ( !s.
value( QStringLiteral(
"/Projections/showDatumTransformDialog" ),
false ).toBool() )
2097 r.
scale( scaleFactor, center );
2119 void QgsMapCanvas::mapToolDestroyed()
2127 if ( !QTouchDevice::devices().empty() )
2129 if ( e->type() == QEvent::Gesture )
2134 return mMapTool->
gestureEvent( static_cast<QGestureEvent *>( e ) );
2140 return QGraphicsView::event( e );
2162 while ( mRefreshScheduled || mJob )
2164 QgsApplication::processEvents();
2180 QList<QgsMapCanvasAnnotationItem *> annotationItemList;
2181 QList<QGraphicsItem *> itemList = mScene->items();
2182 QList<QGraphicsItem *>::iterator it = itemList.begin();
2183 for ( ; it != itemList.end(); ++it )
2188 annotationItemList.push_back( aItem );
2192 return annotationItemList;
2197 mAnnotationsVisible = show;
2200 item->setVisible( show );
2214 void QgsMapCanvas::startPreviewJobs()
2217 schedulePreviewJob( 0 );
2220 void QgsMapCanvas::startPreviewJob(
int number )
2233 double dx = ( i - 1 ) * mapRect.
width();
2234 double dy = ( 1 - j ) * mapRect.
height();
2247 const QList<QgsMapLayer *>
layers = jobSettings.
layers();
2248 QList< QgsMapLayer * > previewLayers;
2256 QgsDebugMsgLevel( QString(
"Layer %1 not rendered because it does not match the renderInPreview criterion %2" ).arg( layer->
id() ).arg( mLastLayerRenderTime.value( layer->
id() ) ), 3 );
2260 previewLayers <<
layer;
2265 job->setProperty(
"number", number );
2266 mPreviewJobs.append( job );
2271 void QgsMapCanvas::stopPreviewJobs()
2273 mPreviewTimer.stop();
2274 QList< QgsMapRendererQImageJob * >::const_iterator it = mPreviewJobs.constBegin();
2275 for ( ; it != mPreviewJobs.constEnd(); ++it )
2281 ( *it )->cancelWithoutBlocking();
2284 mPreviewJobs.clear();
2287 void QgsMapCanvas::schedulePreviewJob(
int number )
2289 mPreviewTimer.setSingleShot(
true );
2290 mPreviewTimer.setInterval( PREVIEW_JOB_DELAY_MS );
2291 disconnect( mPreviewTimerConnection );
2292 mPreviewTimerConnection = connect( &mPreviewTimer, &QTimer::timeout,
this, [ = ]()
2294 startPreviewJob( number );
2297 mPreviewTimer.start();
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...
T enumValue(const QString &key, const T &defaultValue, const Section section=NoSection, bool flag=false) const
Return the setting value for a setting based on an enum.
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.
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
Return the list of layers shown within the map canvas.
bool isNull() const
Returns true if the geometry is null (ie, contains no underlying geometry accessible via geometry() )...
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the stored overrides of styles for rendering layers.
double magnificationFactor() const
Return 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
Overridden standard event to be gestures aware.
QColor selectionColor() const
Returns color for selected features.
bool mouseButtonDown
Flag to indicate status of mouse button.
void wheelEvent(QWheelEvent *e) override
Overridden mouse wheel event.
void canvasColorChanged()
Emitted when canvas background color changes.
QSet< QgsFeatureId > QgsFeatureIds
void stopRendering()
stop rendering (if there is any right now)
void setPreviewJobsEnabled(bool enabled)
Sets whether canvas map preview jobs (low priority render jobs which render portions of the view just...
A class to represent a 2D point.
double rotation() const
Get 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.
int selectedFeatureCount() const
The number of features that are selected in this layer.
QColor backgroundColor() const
Get the background color of the map.
void keyPressEvent(QKeyEvent *e) override
Overridden key press event.
void zoomToFeatureExtent(QgsRectangle &rect)
Zooms to feature extent.
virtual void reload()
Synchronises with changes in the datasource.
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
return 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.
void setFlags(QgsMapSettings::Flags flags)
Set 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 renderComplete(QPainter *)
Emitted when the canvas has rendered.
Snapping utils instance that is connected to a canvas and updates the configuration (map settings + c...
bool isCachingEnabled() const
Check whether images of rendered layers are curerently being cached.
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
Get list of layers for map rendering The layers are stored in the reverse order of how they are rende...
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
void mousePressEvent(QMouseEvent *e) override
Overridden mouse press event.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void mapThemesChanged()
Emitted when map themes within the collection are changed.
bool isEditable() const override
Returns true if the provider is in editing mode.
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
virtual QImage renderedImage()=0
Get a preview/resulting image.
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
Return the actual extent derived from requested extent that takes takes output image size into accoun...
bool qgsDoubleNear(double a, double b, double epsilon=4 *DBL_EPSILON)
Compare two doubles (but allow some difference)
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning)
add a message to the instance (and create it if necessary)
QgsCoordinateTransformContext transformContext() const
Returns a copy of the project's coordinate transform context, which stores various information regard...
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
Get units of map's geographical coordinates - used for scale calculation.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
sets destination coordinate reference system
The QgsMapSettings class contains configuration for rendering of the map.
void resizeEvent(QResizeEvent *e) override
Overridden resize event.
Deprecated to be deleted, stuff from here should be moved elsewhere.
void enableMapTileRendering(bool flag)
sets map tile rendering flag
Perform transforms between map coordinates and device coordinates.
void setSnappingUtils(QgsSnappingUtils *utils)
Assign an instance of snapping utils to the map canvas.
void mapThemeChanged(const QString &theme)
Emitted when a map theme changes definition.
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
Return 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)
Set 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 convtents 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) ...
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.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, const bool clearAndSelect)
This signal is emitted when selection was changed.
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.
virtual void waitForFinished()=0
Block until the job has finished.
double mapUnitsPerPixel() const
Return the distance in geographical coordinates that equals to one pixel in the map.
void readProject(const QDomDocument &)
emitted when 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 panToFeatureIds(QgsVectorLayer *layer, const QgsFeatureIds &ids)
Centers canvas extent to feature ids.
void mouseDoubleClickEvent(QMouseEvent *e) override
Overridden mouse double-click event.
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.
bool isSpatial() const override
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
QgsRectangle layerExtentToOutputExtent(const QgsMapLayer *layer, QgsRectangle extent) const
transform bounding box from layer's CRS to output CRS
void setWheelFactor(double factor)
set wheel zoom factor (should be greater than 1)
QgsCoordinateReferenceSystem crs() const
Returns the layer's spatial reference system.
void destinationCrsChanged()
Emitted when map CRS has 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.
void setCachingEnabled(bool enabled)
Set whether to cache images of rendered layers.
Single scope for storing variables and functions for use within a QgsExpressionContext.
Contains information about the context in which a coordinate transform is executed.
QgsGeometry geometry() const
Returns the geometry associated with this feature.
double mapUnitsPerPixel() const
Return 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.
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.
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.
bool addSourceDestinationDatumTransform(const QgsCoordinateReferenceSystem &sourceCrs, const QgsCoordinateReferenceSystem &destinationCrs, int sourceTransformId, int destinationTransformId)
Adds a new sourceTransform and destinationTransform to use when projecting coordinates from the the s...
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 current (vector) layer.
A class to represent a vector.
PreviewMode mode() const
Returns the mode used for the preview effect.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const override
Query the layer for features specified in request.
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
Overridden mouse move event.
void keyReleaseEvent(QKeyEvent *e) override
Overridden key release event.
void selectionChanged(QgsMapLayer *layer)
Emitted when selection in any layer gets changed.
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
Get access to properties used for map rendering.
void combineExtentWith(const QgsRectangle &rect)
Expand the rectangle so that covers both the original rectangle and the given rectangle.
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.
Render is a 'canvas preview' render, and shortcuts should be taken to ensure fast rendering...
QgsUnitTypes::DistanceUnit mapUnits() const
Convience function for returning the current canvas map units.
void setBackgroundColor(const QColor &color)
Set the background color of the map.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets global configuration of the labeling engine.
void mouseReleaseEvent(QMouseEvent *e) override
Overridden mouse release event.
void writeProject(QDomDocument &)
emitted when project is being written
QgsPointXY toMapPoint(double x, double y) const
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
Get map of map layer style overrides (key: layer ID, value: style name) where a different style shoul...
static QgsExpressionContextScope * atlasScope(QgsLayoutAtlas *atlas)
Creates a new scope which contains variables and functions relating to a QgsLayoutAtlas.
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
Get map center, in geographical coordinates.
void setSelectionColor(const QColor &color)
Set 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
Overridden drag enter event.
void setYMaximum(double y)
Set the maximum y value.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), const Section section=NoSection) const
Returns the value for setting key.
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...
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
Get access to the labeling results (may be null)
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the project's coordinate transform context, which stores various information regarding which dat...
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.
QgsVectorDataProvider * dataProvider() override
Returns the layer's data provider.
void refreshAllLayers()
Reload all layers, clear the cache and refresh the canvas.
void zoomScale(double scale)
Zooms the canvas to a specific scale.
void setExtent(const QgsRectangle &r, bool magnified=false)
Set 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()
Get the current coordinate transform.
void scaleChanged(double)
Emitted when the scale of the map changes.
void setPathResolver(const QgsPathResolver &resolver)
Sets the path resolver for conversion between relative and absolute paths during rendering operations...
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
virtual void cancelWithoutBlocking()=0
Triggers cancelation 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.
void paintEvent(QPaintEvent *e) override
Overridden paint event.
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 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
Get color that is used for drawing of selected vector features.
QgsPointXY center() const
Returns the center point of the rectangle.
QList< int > QgsAttributeList
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.
QgsSnappingUtils * snappingUtils() const
Return snapping utility class that is associated with map canvas.
virtual QgsLabelingResults * takeLabelingResults()=0
Get 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.
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
Return 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
Return the size of the resulting map image.
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
QgsPointXY toMapCoordinates(int x, int y) const
QgsMapLayer * layer(int index)
return the map layer at position index in the layer stack
QString authid() const
Returns the authority identifier for the CRS.
virtual bool isActive() const =0
Tell whether the rendering job is currently running in background.
void setXMinimum(double x)
Set the minimum x value.
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 global configuration of the labeling engine.
void panActionEnd(QPoint releasePoint)
Ends pan action and redraws the canvas.
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)
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
virtual bool usedCachedLabels() const =0
Returns true if the render job was able to use a cached labeling solution.