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();
243 delete mLabelingResults;
251 factor = qBound( magnifierMin, factor, magnifierMax );
280 if ( index >= 0 && index < (
int ) layers.size() )
281 return layers[index];
288 mCurrentLayer =
layer;
299 return nullptr != mJob;
312 if ( !mTheme.isEmpty() )
315 setLayersPrivate( layers );
318 void QgsMapCanvas::setLayersPrivate(
const QList<QgsMapLayer *> &
layers )
320 QList<QgsMapLayer *> oldLayers = mSettings.
layers();
323 if ( layers == oldLayers )
330 if (
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer ) )
344 if (
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer ) )
353 updateAutoRefreshTimer();
375 rect = transform.transformBoundingBox( mSettings.
visibleExtent() );
380 QgsDebugMsg( QString(
"Transform error caught: %1" ).arg( e.
what() ) );
392 QgsDebugMsg(
"refreshing after destination CRS changed" );
407 return mLabelingResults;
434 return nullptr != mCache;
445 mUseParallelRendering = enabled;
450 return mUseParallelRendering;
455 mMapUpdateTimer.setInterval( timeMilliseconds );
460 return mMapUpdateTimer.interval();
466 return mCurrentLayer;
474 QgsDebugMsg(
"CANVAS refresh - invalid settings -> nothing to do" );
478 if ( !mRenderFlag || mFrozen )
484 if ( mRefreshScheduled )
490 mRefreshScheduled =
true;
495 mRefreshTimer->start( 1 );
498 void QgsMapCanvas::refreshMap()
500 Q_ASSERT( mRefreshScheduled );
518 if ( !mTheme.isEmpty() )
531 mJobCanceled =
false;
532 if ( mUseParallelRendering )
547 mRefreshScheduled =
false;
549 mMapUpdateTimer.start();
554 void QgsMapCanvas::mapThemeChanged(
const QString &
theme )
556 if ( theme == mTheme )
561 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
575 void QgsMapCanvas::rendererJobFinished()
577 QgsDebugMsg( QString(
"CANVAS finish! %1" ).arg( !mJobCanceled ) );
579 mMapUpdateTimer.stop();
593 delete mLabelingResults;
604 if ( settings.
value( QStringLiteral(
"Map/logCanvasRefreshEvent" ),
false ).toBool() )
606 QString logMsg = tr(
"Canvas refresh: %1 ms" ).arg( mJob->
renderingTime() );
610 if ( mDrawRenderingStats )
612 int w = img.width(), h = img.height();
613 QFont fnt = p.font();
616 int lh = p.fontMetrics().height() * 2;
617 QRect r( 0, h - lh, w, lh );
618 p.setPen( Qt::NoPen );
619 p.setBrush( QColor( 0, 0, 0, 110 ) );
621 p.setPen( Qt::white );
622 QString msg = QStringLiteral(
"%1 :: %2 ms" ).arg( mUseParallelRendering ?
"PARALLEL" :
"SEQUENTIAL" ).arg( mJob->
renderingTime() );
623 p.drawText( r, msg, QTextOption( Qt::AlignCenter ) );
628 mMap->setContent( img, imageRect( img, mSettings ) );
630 mLastLayerRenderTime.clear();
632 for (
auto it = times.constBegin(); it != times.constEnd(); ++it )
634 mLastLayerRenderTime.insert( it.key()->id(), it.value() );
636 if ( mUsePreviewJobs )
648 void QgsMapCanvas::previewJobFinished()
656 mPreviewJobs.removeAll( job );
658 int number = job->property(
"number" ).toInt();
661 startPreviewJob( number + 1 );
675 QgsRectangle rect( topLeft.
x(), topLeft.
y(), topLeft.
x() + img.width()*res, topLeft.
y() - img.height()*res );
681 return mUsePreviewJobs;
686 mUsePreviewJobs = enabled;
689 void QgsMapCanvas::mapUpdateTimeout()
694 mMap->setContent( img, imageRect( img, mSettings ) );
723 image = theQPixmap->toImage();
724 painter.begin( &image );
734 image = mMap->contentImage().copy();
735 painter.begin( &image );
739 QStyleOptionGraphicsItem option;
740 option.initFrom(
this );
741 QGraphicsItem *item =
nullptr;
742 QListIterator<QGraphicsItem *> i( items() );
744 while ( i.hasPrevious() )
748 if ( !item || dynamic_cast< QgsMapCanvasAnnotationItem * >( item ) )
755 QPointF itemScenePos = item->scenePos();
756 painter.translate( itemScenePos.x(), itemScenePos.y() );
758 item->paint( &painter, &option );
764 image.save( fileName, format.toLocal8Bit().data() );
766 QFileInfo myInfo = QFileInfo( fileName );
769 QString outputSuffix = myInfo.suffix();
770 QString myWorldFileName = myInfo.absolutePath() +
'/' + myInfo.baseName() +
'.' 771 + outputSuffix.at( 0 ) + outputSuffix.at( myInfo.suffix().size() - 1 ) +
'w';
772 QFile myWorldFile( myWorldFileName );
773 if ( !myWorldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
777 QTextStream myStream( &myWorldFile );
798 if ( ( r == current ) && magnified )
811 QgsDebugMsg(
"Empty extent - keeping old scale with new center!" );
820 if ( mLastExtent.size() > 20 )
821 mLastExtent.removeAt( 0 );
824 for (
int i = mLastExtent.size() - 1; i > mLastExtentIndex; i-- )
826 mLastExtent.removeAt( i );
829 mLastExtent.append(
extent() );
832 if ( mLastExtent.size() > 20 )
834 mLastExtent.removeAt( 0 );
838 mLastExtentIndex = mLastExtent.size() - 1;
848 double x = center.
x();
849 double y = center.
y();
875 if ( degrees == current )
897 extent.
scale( 1.05 );
907 if ( mLastExtentIndex > 0 )
910 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
923 if ( mLastExtentIndex < mLastExtent.size() - 1 )
926 mSettings.
setExtent( mLastExtent[mLastExtentIndex] );
939 mLastExtent.append(
extent() ) ;
940 mLastExtentIndex = mLastExtent.size() - 1;
977 rect.
scale( 1.0, &c );
1001 if ( boundingBoxOfFeatureIds( ids, layer, bbox, errorMsg ) )
1021 if ( boundingBoxOfFeatureIds( ids, layer, bbox, errorMsg ) )
1037 int featureCount = 0;
1045 errorMsg = tr(
"Feature does not have a geometry" );
1049 errorMsg = tr(
"Feature geometry is empty" );
1051 if ( !errorMsg.isEmpty() )
1060 if ( featureCount != ids.count() )
1062 errorMsg = tr(
"Feature not found" );
1093 const QColor &color1,
const QColor &color2,
1094 int flashes,
int duration )
1101 QList< QgsGeometry > geoms;
1117 if ( geometries.isEmpty() )
1123 rb->addGeometry( geom, crs );
1128 rb->setSecondaryStrokeColor( QColor( 255, 255, 255 ) );
1133 QColor startColor = color1;
1134 if ( !startColor.isValid() )
1138 startColor = rb->fillColor();
1142 startColor = rb->strokeColor();
1144 startColor.setAlpha( 255 );
1146 QColor endColor = color2;
1147 if ( !endColor.isValid() )
1149 endColor = startColor;
1150 endColor.setAlpha( 0 );
1154 QVariantAnimation *animation =
new QVariantAnimation(
this );
1155 connect( animation, &QVariantAnimation::finished,
this, [animation, rb]
1157 animation->deleteLater();
1160 connect( animation, &QPropertyAnimation::valueChanged,
this, [rb, geomType](
const QVariant & value )
1162 QColor
c = value.value<QColor>();
1165 rb->setFillColor( c );
1169 rb->setStrokeColor( c );
1170 QColor c = rb->secondaryStrokeColor();
1171 c.setAlpha( c.alpha() );
1172 rb->setSecondaryStrokeColor( c );
1177 animation->setDuration( duration * flashes );
1178 animation->setStartValue( endColor );
1179 double midStep = 0.2 / flashes;
1180 for (
int i = 0; i < flashes; ++i )
1182 double start =
static_cast< double >( i ) / flashes;
1183 animation->setKeyValueAt( start + midStep, startColor );
1184 double end =
static_cast< double >( i + 1 ) / flashes;
1186 animation->setKeyValueAt( end, endColor );
1188 animation->setEndValue( endColor );
1205 double dx = std::fabs( currentExtent.
width() / 4 );
1206 double dy = std::fabs( currentExtent.
height() / 4 );
1240 if ( ! e->isAutoRepeat() )
1242 QApplication::setOverrideCursor( Qt::ClosedHandCursor );
1248 case Qt::Key_PageUp:
1253 case Qt::Key_PageDown:
1260 mUseParallelRendering = !mUseParallelRendering;
1265 mDrawRenderingStats = !mDrawRenderingStats;
1278 QgsDebugMsg(
"Ignoring key: " + QString::number( e->key() ) );
1296 QApplication::restoreOverrideCursor();
1310 QgsDebugMsg(
"Ignoring key release: " + QString::number( e->key() ) );
1329 void QgsMapCanvas::beginZoomRect( QPoint pos )
1331 mZoomRect.setRect( 0, 0, 0, 0 );
1332 QApplication::setOverrideCursor( mZoomCursor );
1333 mZoomDragging =
true;
1335 QColor color( Qt::blue );
1336 color.setAlpha( 63 );
1337 mZoomRubberBand->setColor( color );
1338 mZoomRect.setTopLeft( pos );
1341 void QgsMapCanvas::endZoomRect( QPoint pos )
1343 mZoomDragging =
false;
1344 mZoomRubberBand.reset(
nullptr );
1345 QApplication::restoreOverrideCursor();
1348 mZoomRect.setRight( pos.x() );
1349 mZoomRect.setBottom( pos.y() );
1351 if ( mZoomRect.width() < 5 && mZoomRect.height() < 5 )
1358 mZoomRect = mZoomRect.normalized();
1361 const QSize &zoomRectSize = mZoomRect.size();
1362 const QSize &canvasSize = mSettings.
outputSize();
1363 double sfx = ( double )zoomRectSize.width() / canvasSize.width();
1364 double sfy = ( double )zoomRectSize.height() / canvasSize.height();
1365 double sf = std::max( sfx, sfy );
1376 if ( e->button() == Qt::MidButton )
1387 && e->modifiers() & Qt::ShiftModifier )
1389 beginZoomRect( e->pos() );
1414 if ( e->button() == Qt::MidButton )
1419 else if ( e->button() == Qt::BackButton )
1424 else if ( e->button() == Qt::ForwardButton )
1431 if ( mZoomDragging && e->button() == Qt::LeftButton )
1433 endZoomRect( e->pos() );
1443 QgsDebugMsg(
"Right click in map tool zoom or pan, last tool is " +
1444 QString( mLastNonZoomMapTool ?
"not null." :
"null." ) );
1449 if ( mLastNonZoomMapTool
1454 mLastNonZoomMapTool =
nullptr;
1474 QGraphicsView::resizeEvent( e );
1475 mResizeTimer->start( 500 );
1477 QSize lastSize = viewport()->size();
1481 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
1496 QGraphicsView::paintEvent( e );
1501 QList<QGraphicsItem *> list = mScene->items();
1502 QList<QGraphicsItem *>::iterator it = list.begin();
1503 while ( it != list.end() )
1522 QgsDebugMsg(
"Wheel event delta " + QString::number( e->delta() ) );
1527 if ( e->isAccepted() )
1531 double zoomFactor = mWheelZoomFactor;
1534 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( e->angleDelta().y() );
1536 if ( e->modifiers() & Qt::ControlModifier )
1539 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
1542 double signedWheelFactor = e->angleDelta().y() > 0 ? 1 / zoomFactor : zoomFactor;
1547 QgsPointXY newCenter( mousePos.
x() + ( ( oldCenter.
x() - mousePos.
x() ) * signedWheelFactor ),
1548 mousePos.
y() + ( ( oldCenter.
y() - mousePos.
y() ) * signedWheelFactor ) );
1556 mWheelZoomFactor = factor;
1578 double scaleFactor = ( zoomIn ? 1 / mWheelZoomFactor : mWheelZoomFactor );
1589 r.
scale( scaleFactor, ¢er );
1597 mScaleLocked = isLocked;
1608 else if ( mZoomDragging )
1610 mZoomRect.setBottomRight( e->pos() );
1611 mZoomRubberBand->setToCanvasRectangle( mZoomRect );
1612 mZoomRubberBand->show();
1625 QPoint xy = e->pos();
1640 disconnect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
1650 mLastNonZoomMapTool = mMapTool;
1654 mLastNonZoomMapTool =
nullptr;
1663 connect( mMapTool, &QObject::destroyed,
this, &QgsMapCanvas::mapToolDestroyed );
1672 if ( mMapTool && mMapTool == tool )
1677 setCursor( Qt::ArrowCursor );
1680 if ( mLastNonZoomMapTool && mLastNonZoomMapTool == tool )
1682 mLastNonZoomMapTool =
nullptr;
1695 QBrush bgBrush( color );
1696 setBackgroundBrush( bgBrush );
1699 palette.setColor( backgroundRole(), color );
1700 setPalette( palette );
1704 mScene->setBackgroundBrush( bgBrush );
1711 return mScene->backgroundBrush().color();
1778 if ( mTheme == theme )
1792 setLayersPrivate(
QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( mTheme ) );
1810 void QgsMapCanvas::connectNotify(
const char *signal )
1813 QgsDebugMsg(
"QgsMapCanvas connected to " + QString( signal ) );
1817 void QgsMapCanvas::layerRepaintRequested(
bool deferred )
1823 void QgsMapCanvas::autoRefreshTriggered()
1836 void QgsMapCanvas::updateAutoRefreshTimer()
1840 int minAutoRefreshInterval = -1;
1847 if ( minAutoRefreshInterval > 0 )
1849 mAutoRefreshTimer.setInterval( minAutoRefreshInterval );
1850 mAutoRefreshTimer.start();
1854 mAutoRefreshTimer.stop();
1858 void QgsMapCanvas::projectThemesChanged()
1860 if ( mTheme.isEmpty() )
1886 double dx = end.
x() - start.
x();
1887 double dy = end.
y() - start.
y();
1889 c.
set( c.
x() - dx, c.
y() - dy );
1909 setSceneRect( -pnt.x(), -pnt.y(), viewport()->size().width(), viewport()->size().height() );
1919 if ( !mPreviewEffect )
1924 mPreviewEffect->setEnabled( previewEnabled );
1929 if ( !mPreviewEffect )
1934 return mPreviewEffect->isEnabled();
1939 if ( !mPreviewEffect )
1944 mPreviewEffect->
setMode( mode );
1949 if ( !mPreviewEffect )
1954 return mPreviewEffect->
mode();
1959 if ( !mSnappingUtils )
1965 return mSnappingUtils;
1970 mSnappingUtils = utils;
1975 QDomNodeList nodes = doc.elementsByTagName( QStringLiteral(
"mapcanvas" ) );
1976 if ( nodes.count() )
1978 QDomNode node = nodes.item( 0 );
1981 if ( nodes.count() > 1 )
1983 for (
int i = 0; i < nodes.size(); ++i )
1985 QDomElement elementNode = nodes.at( i ).toElement();
1987 if ( elementNode.hasAttribute( QStringLiteral(
"name" ) ) && elementNode.attribute( QStringLiteral(
"name" ) ) == objectName() )
1989 node = nodes.at( i );
1997 if ( objectName() != QStringLiteral(
"theMapCanvas" ) )
2008 QDomElement elem = node.toElement();
2009 if ( elem.hasAttribute( QStringLiteral(
"theme" ) ) )
2013 setTheme( elem.attribute( QStringLiteral(
"theme" ) ) );
2016 setAnnotationsVisible( elem.attribute( QStringLiteral(
"annotationsVisible" ), QStringLiteral(
"1" ) ).toInt() );
2020 QgsDebugMsg(
"Couldn't read mapcanvas information from project" );
2028 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
2031 QgsDebugMsg(
"Unable to find qgis element in project file" );
2034 QDomNode qgisNode = nl.item( 0 );
2036 QDomElement mapcanvasNode = doc.createElement( QStringLiteral(
"mapcanvas" ) );
2037 mapcanvasNode.setAttribute( QStringLiteral(
"name" ), objectName() );
2038 if ( !mTheme.isEmpty() )
2039 mapcanvasNode.setAttribute( QStringLiteral(
"theme" ), mTheme );
2040 mapcanvasNode.setAttribute( QStringLiteral(
"annotationsVisible" ), mAnnotationsVisible );
2041 qgisNode.appendChild( mapcanvasNode );
2043 mSettings.
writeXml( mapcanvasNode, doc );
2055 QString settingsString =
"/Projections/" + source.
authid() +
"//" + destination.
authid();
2056 QVariant defaultSrcTransform = s.
value( settingsString +
"_srcTransform" );
2057 QVariant defaultDestTransform = s.
value( settingsString +
"_destTransform" );
2058 if ( defaultSrcTransform.isValid() && defaultDestTransform.isValid() )
2060 int sourceDatumTransform = defaultSrcTransform.toInt();
2061 int destinationDatumTransform = defaultDestTransform.toInt();
2069 if ( !s.
value( QStringLiteral(
"/Projections/showDatumTransformDialog" ),
false ).toBool() )
2091 r.
scale( scaleFactor, center );
2116 void QgsMapCanvas::mapToolDestroyed()
2124 if ( !QTouchDevice::devices().empty() )
2126 if ( e->type() == QEvent::Gesture )
2131 return mMapTool->
gestureEvent( static_cast<QGestureEvent *>( e ) );
2137 return QGraphicsView::event( e );
2159 while ( mRefreshScheduled || mJob )
2161 QgsApplication::processEvents();
2177 QList<QgsMapCanvasAnnotationItem *> annotationItemList;
2178 QList<QGraphicsItem *> itemList = mScene->items();
2179 QList<QGraphicsItem *>::iterator it = itemList.begin();
2180 for ( ; it != itemList.end(); ++it )
2185 annotationItemList.push_back( aItem );
2189 return annotationItemList;
2194 mAnnotationsVisible = show;
2197 item->setVisible( show );
2211 void QgsMapCanvas::startPreviewJobs()
2214 schedulePreviewJob( 0 );
2217 void QgsMapCanvas::startPreviewJob(
int number )
2230 double dx = ( i - 1 ) * mapRect.
width();
2231 double dy = ( 1 - j ) * mapRect.
height();
2244 const QList<QgsMapLayer *>
layers = jobSettings.
layers();
2245 QList< QgsMapLayer * > previewLayers;
2253 QgsDebugMsgLevel( QString(
"Layer %1 not rendered because it does not match the renderInPreview criterion %2" ).arg( layer->
id() ).arg( mLastLayerRenderTime.value( layer->
id() ) ), 3 );
2257 previewLayers <<
layer;
2262 job->setProperty(
"number", number );
2263 mPreviewJobs.append( job );
2268 void QgsMapCanvas::stopPreviewJobs()
2270 mPreviewTimer.stop();
2271 QList< QgsMapRendererQImageJob * >::const_iterator it = mPreviewJobs.constBegin();
2272 for ( ; it != mPreviewJobs.constEnd(); ++it )
2278 ( *it )->cancelWithoutBlocking();
2281 mPreviewJobs.clear();
2284 void QgsMapCanvas::schedulePreviewJob(
int number )
2286 mPreviewTimer.setSingleShot(
true );
2287 mPreviewTimer.setInterval( PREVIEW_JOB_DELAY_MS );
2288 disconnect( mPreviewTimerConnection );
2289 mPreviewTimerConnection = connect( &mPreviewTimer, &QTimer::timeout,
this, [ = ]()
2291 startPreviewJob( number );
2293 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...
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
Returns 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
Returns the magnification factor.
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
void setXMaximum(double x)
Set the maximum x value.
void clearExtentHistory()
This class is a composition of two QSettings instances:
Maximum angle between generating radii (lines from arc center to output vertices) ...
bool event(QEvent *e) override
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.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
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
Gets the current map canvas rotation in clockwise degrees.
QgsPreviewEffect::PreviewMode previewMode() const
Returns the current preview mode for the map canvas.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
QColor backgroundColor() const
Gets 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
Returns number of layers on the map.
Errors errors() const
List of errors that happened during the rendering job - available when the rendering has been finishe...
void moveCanvasContents(bool reset=false)
called when panning is in action, reset indicates end of panning
A QgsMapMouseEvent is the result of a user interaction with the mouse on a QgsMapCanvas.
void setFlags(QgsMapSettings::Flags flags)
Sets combination of flags that will be used for rendering.
void setAnnotationsVisible(bool visible)
Sets whether annotations are visible in the canvas.
constexpr double CANVAS_MAGNIFICATION_MAX
Maximum magnification level allowed in map canvases.
void readProject(const QDomDocument &)
called to read map canvas settings from project
bool panSelectorDown
Flag to indicate the pan selector key is held down by user.
void refresh()
Repaints the canvas map.
A geometry is the spatial representation of a feature.
void 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
Gets list of layers for map rendering The layers are stored in the reverse order of how they are rend...
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
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
Gets 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
Returns the actual extent derived from requested extent that takes takes output image size into accou...
void selectionChanged(QgsVectorLayer *layer)
Emitted when selection in any layer gets changed.
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
Gets 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
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
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
Returns geographical coordinates of the rectangle that should be rendered.
void setMapTool(QgsMapTool *mapTool, bool clean=false)
Sets the map tool currently being used on the canvas.
void setOutputSize(QSize size)
Sets the size of the resulting map image.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context...
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
double mapUnitsPerPixel() const
Returns the mapUnitsPerPixel (map units per pixel) for the canvas.
void start() override
Start the rendering job and immediately return.
void saveAsImage(const QString &fileName, QPixmap *QPixmap=nullptr, const QString &="PNG")
Save the 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.
double width() const
Returns the width of the rectangle.
void setYMinimum(double y)
Set the minimum y value.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setSegmentationTolerance(double tolerance)
Sets the segmentation tolerance applied when rendering curved geometries.
void setMapUpdateInterval(int timeMilliseconds)
Set how often map preview should be updated while it is being rendered (in milliseconds) ...
void keyReleased(QKeyEvent *e)
Emit key release event.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
virtual void waitForFinished()=0
Block until the job has finished.
double mapUnitsPerPixel() const
Returns the distance in geographical coordinates that equals to one pixel in the map.
void readProject(const QDomDocument &)
Emitted when a project is being read.
Enable anti-aliasing for map rendering.
QgsRectangle extent() const
Returns the current zoom extent of the map canvas.
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
void 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)
Sets 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.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
This signal is emitted when selection was changed.
bool hasValidSettings() const
Check whether the map settings are valid and can be used for rendering.
bool isFrozen() const
Returns true if canvas is frozen.
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
Returns current map units per pixel.
void setPreviewMode(QgsPreviewEffect::PreviewMode mode)
Sets a preview mode for the map canvas.
QHash< QgsMapLayer *, int > perLayerRenderingTime() const
Returns the render time (in ms) per layer.
void transformContextChanged()
Emitted when the canvas transform context is changed.
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 speci...
virtual bool renderInPreview(const QgsDataProvider::PreviewContext &context)
Returns whether the layer must be rendered in preview jobs.
void zoomToSelected(QgsVectorLayer *layer=nullptr)
Zoom to the extent of the selected features of provided (vector) layer.
A class to represent a vector.
PreviewMode mode() const
Returns the mode used for the preview effect.
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.
DistanceUnit
Units of distance.
void flashGeometries(const QList< QgsGeometry > &geometries, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), const QColor &startColor=QColor(255, 0, 0, 255), const QColor &endColor=QColor(255, 0, 0, 0), int flashes=3, int duration=500)
Causes a set of geometries to flash within the canvas.
double scale() const
Returns the last reported scale of the canvas.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle...
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
Convenience function for returning the current canvas map units.
void setBackgroundColor(const QColor &color)
Sets the background color of the map.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets global configuration of the labeling engine.
void mouseReleaseEvent(QMouseEvent *e) override
Overridden mouse release event.
void writeProject(QDomDocument &)
Emitted when the 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
Gets map of map layer style overrides (key: layer ID, value: style name) where a different style shou...
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
Gets map center, in geographical coordinates.
void setSelectionColor(const QColor &color)
Sets color that is used for drawing of selected vector features.
void layerStyleOverridesChanged()
Emitted when the configuration of overridden layer styles changes.
void dragEnterEvent(QDragEnterEvent *e) override
Overridden drag enter event.
void setYMaximum(double y)
Set the maximum y value.
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
Gets 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)
Sets the extent of the map canvas.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
void setLayers(const QList< QgsMapLayer *> &layers)
Set list of layers for map rendering.
const QgsMapToPixel * getCoordinateTransform()
Gets the current coordinate transform.
void scaleChanged(double)
Emitted when the scale of the map changes.
void setPathResolver(const QgsPathResolver &resolver)
Sets the path resolver for conversion between relative and absolute paths during rendering operations...
T enumValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on an enum.
void setSegmentationToleranceType(QgsAbstractGeometry::SegmentationToleranceType type)
Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation...
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
Gets 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
Returns snapping utility class that is associated with map canvas.
virtual QgsLabelingResults * takeLabelingResults()=0
Gets pointer to internal labeling engine (in order to get access to the results). ...
void xyCoordinates(const QgsPointXY &p)
Emits current mouse position.
void autoRefreshIntervalChanged(int interval)
Emitted when the auto refresh interval changes.
void writeXml(QDomNode &node, QDomDocument &doc)
void zoomIn()
Zoom in with fixed factor.
Stores settings related to the context in which a preview job runs.
void waitForFinished() override
Block until the job has finished.
Represents a vector layer which manages a vector based data sets.
virtual void updatePosition()
called on changed extent or resize event to update position of the item
bool isParallelRenderingEnabled() const
Check whether the layers are rendered in parallel or sequentially.
const QgsMapSettings & mapSettings() const
Returns map settings with which this job was started.
void mapToolSet(QgsMapTool *newTool, QgsMapTool *oldTool)
Emit map tool changed with the old tool.
CanvasProperties()=default
Constructor for CanvasProperties.
An interactive map canvas item which displays a QgsAnnotation.
void themeChanged(const QString &theme)
Emitted when the canvas has been assigned a different map theme.
void extentsChanged()
Emitted when the extents of the map change.
QSize outputSize() const
Returns the size of the resulting map image.
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
QgsPointXY toMapCoordinates(int x, int y) const
QgsMapLayer * layer(int index)
Returns 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.