QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgselevationprofilecanvas.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgselevationprofilecanvas.cpp
3 -----------------
4 begin : March 2022
5 copyright : (C) 2022 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7***************************************************************************/
8
9
10/***************************************************************************
11 * *
12 * This program is free software; you can redistribute it and/or modify *
13 * it under the terms of the GNU General Public License as published by *
14 * the Free Software Foundation; either version 2 of the License, or *
15 * (at your option) any later version. *
16 * *
17 ***************************************************************************/
18
20
23#include "qgsapplication.h"
24#include "qgscurve.h"
26#include "qgsfillsymbol.h"
27#include "qgsgeos.h"
30#include "qgsmessagelog.h"
31#include "qgsnumericformat.h"
32#include "qgspainting.h"
33#include "qgsplot.h"
34#include "qgsplotcanvasitem.h"
35#include "qgspoint.h"
36#include "qgsprofilerenderer.h"
37#include "qgsprofilerequest.h"
38#include "qgsprofilesnapping.h"
41#include "qgsscreenhelper.h"
43#include "qgsterrainprovider.h"
44
45#include <QPalette>
46#include <QString>
47#include <QTimer>
48#include <QWheelEvent>
49
50#include "moc_qgselevationprofilecanvas.cpp"
51
52using namespace Qt::StringLiterals;
53
55class QgsElevationProfilePlotItem : public Qgs2DXyPlot, public QgsPlotCanvasItem
56{
57 public:
58 QgsElevationProfilePlotItem( QgsElevationProfileCanvas *canvas )
59 : QgsPlotCanvasItem( canvas )
60 {
61 setYMinimum( 0 );
62 setYMaximum( 100 );
63
65 }
66
67 void setRenderer( QgsProfilePlotRenderer *renderer ) { mRenderer = renderer; }
68
69 void updateRect()
70 {
71 mRect = mCanvas->rect();
72 setSize( mRect.size() );
73
74 prepareGeometryChange();
75 setPos( mRect.topLeft() );
76
77 mImage = QImage();
78 mCachedImages.clear();
79 mPlotArea = QRectF();
80 update();
81 }
82
83 void updatePlot()
84 {
85 mImage = QImage();
86 mCachedImages.clear();
87 mPlotArea = QRectF();
88 update();
89 }
90
91 bool redrawResults( const QString &sourceId )
92 {
93 auto it = mCachedImages.find( sourceId );
94 if ( it == mCachedImages.end() )
95 return false;
96
97 mCachedImages.erase( it );
98 mImage = QImage();
99 return true;
100 }
101
102 QRectF boundingRect() const override { return mRect; }
103
104 QString distanceSuffix() const
105 {
106 switch ( mDistanceUnit )
107 {
156 return u" %1"_s.arg( QgsUnitTypes::toAbbreviatedString( mDistanceUnit ) );
157
159 return QObject::tr( "°" );
161 return QString();
162 }
164 }
165
166 void setXAxisUnits( Qgis::DistanceUnit unit )
167 {
168 mDistanceUnit = unit;
169 xAxis().setLabelSuffix( distanceSuffix() );
170 update();
171 }
172
173 QRectF plotArea()
174 {
175 if ( !mPlotArea.isNull() )
176 return mPlotArea;
177
178 // force immediate recalculation of plot area
179 QgsRenderContext context;
180 if ( !scene()->views().isEmpty() )
181 context.setScaleFactor( scene()->views().at( 0 )->logicalDpiX() / 25.4 );
182
183 QgsPlotRenderContext plotContext;
184 calculateOptimisedIntervals( context, plotContext );
185 mPlotArea = interiorPlotArea( context, plotContext );
186 return mPlotArea;
187 }
188
189 QgsProfilePoint canvasPointToPlotPoint( QPointF point )
190 {
191 const QRectF area = plotArea();
192 if ( !area.contains( point.x(), point.y() ) )
193 return QgsProfilePoint();
194
195 const double distance = ( point.x() - area.left() ) / area.width() * ( xMaximum() - xMinimum() ) * mXScaleFactor + xMinimum() * mXScaleFactor;
196 const double elevation = ( area.bottom() - point.y() ) / area.height() * ( yMaximum() - yMinimum() ) + yMinimum();
197 return QgsProfilePoint( distance, elevation );
198 }
199
200 QgsPointXY plotPointToCanvasPoint( const QgsProfilePoint &point )
201 {
202 if ( point.distance() < xMinimum() * mXScaleFactor || point.distance() > xMaximum() * mXScaleFactor || point.elevation() < yMinimum() || point.elevation() > yMaximum() )
203 return QgsPointXY();
204
205 const QRectF area = plotArea();
206
207 const double x = ( point.distance() - xMinimum() * mXScaleFactor ) / ( ( xMaximum() - xMinimum() ) * mXScaleFactor ) * ( area.width() ) + area.left();
208 const double y = area.bottom() - ( point.elevation() - yMinimum() ) / ( yMaximum() - yMinimum() ) * ( area.height() );
209 return QgsPointXY( x, y );
210 }
211
212 void renderContent( QgsRenderContext &rc, QgsPlotRenderContext &, const QRectF &plotArea, const QgsPlotData & ) override
213 {
214 mPlotArea = plotArea;
215
216 if ( !mRenderer )
217 return;
218
219 const double pixelRatio = !scene()->views().empty() ? scene()->views().at( 0 )->devicePixelRatioF() : 1;
220
221 const QStringList sourceIds = mRenderer->sourceIds();
222 for ( const QString &source : sourceIds )
223 {
224 QImage plot;
225 auto it = mCachedImages.constFind( source );
226 if ( it != mCachedImages.constEnd() )
227 {
228 plot = it.value();
229 }
230 else
231 {
232 plot = mRenderer->renderToImage( plotArea.width() * pixelRatio, plotArea.height() * pixelRatio, xMinimum() * mXScaleFactor, xMaximum() * mXScaleFactor, yMinimum(), yMaximum(), source, pixelRatio );
233 plot.setDevicePixelRatio( pixelRatio );
234 mCachedImages.insert( source, plot );
235 }
236 rc.painter()->drawImage( QPointF( plotArea.left(), plotArea.top() ), plot );
237 }
238 }
239
241 void paint( QPainter *painter ) override
242 {
243 // cache rendering to an image, so we don't need to redraw the plot
244 if ( !mImage.isNull() )
245 {
246 painter->drawImage( QPointF( 0, 0 ), mImage );
247 }
248 else
249 {
250 const double pixelRatio = !scene()->views().empty() ? scene()->views().at( 0 )->devicePixelRatioF() : 1;
251 mImage = QImage( mRect.width() * pixelRatio, mRect.height() * pixelRatio, QImage::Format_ARGB32_Premultiplied );
252 mImage.setDevicePixelRatio( pixelRatio );
253 mImage.fill( Qt::transparent );
254
255 QPainter imagePainter( &mImage );
256 imagePainter.setRenderHint( QPainter::Antialiasing, true );
257 QgsRenderContext rc = QgsRenderContext::fromQPainter( &imagePainter );
258 rc.setDevicePixelRatio( pixelRatio );
259
260 const double mapUnitsPerPixel = ( xMaximum() - xMinimum() ) * mXScaleFactor / plotArea().width();
261 rc.setMapToPixel( QgsMapToPixel( mapUnitsPerPixel ) );
262
265
266 QgsPlotRenderContext plotContext;
267 calculateOptimisedIntervals( rc, plotContext );
268 render( rc, plotContext );
269 imagePainter.end();
270
271 painter->drawImage( QPointF( 0, 0 ), mImage );
272 }
273 }
274
275 void setSubsectionsSymbol( QgsLineSymbol *symbol )
276 {
277 if ( mRenderer )
278 {
279 mRenderer->setSubsectionsSymbol( symbol );
280 updatePlot();
281 }
282 }
283
284 QgsProject *mProject = nullptr;
285 double mXScaleFactor = 1.0;
286
288
289 private:
290 QImage mImage;
291
292 QMap<QString, QImage> mCachedImages;
293
294 QRectF mRect;
295 QRectF mPlotArea;
296 QgsProfilePlotRenderer *mRenderer = nullptr;
297};
298
299class QgsElevationProfileCrossHairsItem : public QgsPlotCanvasItem
300{
301 public:
302 QgsElevationProfileCrossHairsItem( QgsElevationProfileCanvas *canvas, QgsElevationProfilePlotItem *plotItem )
303 : QgsPlotCanvasItem( canvas )
304 , mPlotItem( plotItem )
305 {}
306
307 void updateRect()
308 {
309 mRect = mCanvas->rect();
310
311 prepareGeometryChange();
312 setPos( mRect.topLeft() );
313 update();
314 }
315
316 void setPoint( const QgsProfilePoint &point )
317 {
318 mPoint = point;
319 update();
320 }
321
322 QRectF boundingRect() const override { return mRect; }
323
325 void paint( QPainter *painter ) override
326 {
327 const QgsPointXY crossHairPlotPoint = mPlotItem->plotPointToCanvasPoint( mPoint );
328 if ( crossHairPlotPoint.isEmpty() )
329 return;
330
331 QgsScopedQPainterState painterState( painter );
332 painter->setBrush( Qt::NoBrush );
333 QPen crossHairPen;
334 crossHairPen.setCosmetic( true );
335 crossHairPen.setWidthF( 1 );
336 crossHairPen.setStyle( Qt::DashLine );
337 crossHairPen.setCapStyle( Qt::FlatCap );
338 const QPalette scenePalette = mPlotItem->scene()->palette();
339 QColor penColor = scenePalette.color( QPalette::ColorGroup::Active, QPalette::Text );
340 penColor.setAlpha( 150 );
341 crossHairPen.setColor( penColor );
342 painter->setPen( crossHairPen );
343 painter->drawLine( QPointF( mPlotItem->plotArea().left(), crossHairPlotPoint.y() ), QPointF( mPlotItem->plotArea().right(), crossHairPlotPoint.y() ) );
344 painter->drawLine( QPointF( crossHairPlotPoint.x(), mPlotItem->plotArea().top() ), QPointF( crossHairPlotPoint.x(), mPlotItem->plotArea().bottom() ) );
345
346 // also render current point text
347 QgsNumericFormatContext numericContext;
348
349 const QString xCoordinateText = mPlotItem->xAxis().numericFormat()->formatDouble( mPoint.distance() / mPlotItem->mXScaleFactor, numericContext ) + mPlotItem->distanceSuffix();
350
351 const QString yCoordinateText = mPlotItem->yAxis().numericFormat()->formatDouble( mPoint.elevation(), numericContext );
352
353 QFont font;
354 const QFontMetrics fm( font );
355 const double height = fm.capHeight();
356 const double xWidth = fm.horizontalAdvance( xCoordinateText );
357 const double yWidth = fm.horizontalAdvance( yCoordinateText );
358 const double textAxisMargin = fm.horizontalAdvance( ' ' );
359
360 QPointF xCoordOrigin;
361 QPointF yCoordOrigin;
362
363 if ( mPoint.distance() < ( mPlotItem->xMaximum() + mPlotItem->xMinimum() ) * 0.5 * mPlotItem->mXScaleFactor )
364 {
365 if ( mPoint.elevation() < ( mPlotItem->yMaximum() + mPlotItem->yMinimum() ) * 0.5 )
366 {
367 // render x coordinate on right top (left top align)
368 xCoordOrigin = QPointF( crossHairPlotPoint.x() + textAxisMargin, mPlotItem->plotArea().top() + height + textAxisMargin );
369 // render y coordinate on right top (right bottom align)
370 yCoordOrigin = QPointF( mPlotItem->plotArea().right() - yWidth - textAxisMargin, crossHairPlotPoint.y() - textAxisMargin );
371 }
372 else
373 {
374 // render x coordinate on right bottom (left bottom align)
375 xCoordOrigin = QPointF( crossHairPlotPoint.x() + textAxisMargin, mPlotItem->plotArea().bottom() - textAxisMargin );
376 // render y coordinate on right bottom (right top align)
377 yCoordOrigin = QPointF( mPlotItem->plotArea().right() - yWidth - textAxisMargin, crossHairPlotPoint.y() + height + textAxisMargin );
378 }
379 }
380 else
381 {
382 if ( mPoint.elevation() < ( mPlotItem->yMaximum() + mPlotItem->yMinimum() ) * 0.5 )
383 {
384 // render x coordinate on left top (right top align)
385 xCoordOrigin = QPointF( crossHairPlotPoint.x() - xWidth - textAxisMargin, mPlotItem->plotArea().top() + height + textAxisMargin );
386 // render y coordinate on left top (left bottom align)
387 yCoordOrigin = QPointF( mPlotItem->plotArea().left() + textAxisMargin, crossHairPlotPoint.y() - textAxisMargin );
388 }
389 else
390 {
391 // render x coordinate on left bottom (right bottom align)
392 xCoordOrigin = QPointF( crossHairPlotPoint.x() - xWidth - textAxisMargin, mPlotItem->plotArea().bottom() - textAxisMargin );
393 // render y coordinate on left bottom (left top align)
394 yCoordOrigin = QPointF( mPlotItem->plotArea().left() + textAxisMargin, crossHairPlotPoint.y() + height + textAxisMargin );
395 }
396 }
397
398 // semi opaque background color brush
399 QColor backgroundColor = mPlotItem->chartBackgroundSymbol()->color();
400 backgroundColor.setAlpha( 220 );
401 painter->setBrush( QBrush( backgroundColor ) );
402 painter->setPen( Qt::NoPen );
403 painter->drawRect( QRectF( xCoordOrigin.x() - textAxisMargin + 1, xCoordOrigin.y() - textAxisMargin - height + 1, xWidth + 2 * textAxisMargin - 2, height + 2 * textAxisMargin - 2 ) );
404 painter->drawRect( QRectF( yCoordOrigin.x() - textAxisMargin + 1, yCoordOrigin.y() - textAxisMargin - height + 1, yWidth + 2 * textAxisMargin - 2, height + 2 * textAxisMargin - 2 ) );
405
406 painter->setBrush( Qt::NoBrush );
407 painter->setPen( scenePalette.color( QPalette::ColorGroup::Active, QPalette::Text ) );
408
409 painter->drawText( xCoordOrigin, xCoordinateText );
410 painter->drawText( yCoordOrigin, yCoordinateText );
411 }
412
413 private:
414 QRectF mRect;
415 QgsProfilePoint mPoint;
416 QgsElevationProfilePlotItem *mPlotItem = nullptr;
417};
419
420
422 : QgsPlotCanvas( parent )
423{
424 mScreenHelper = new QgsScreenHelper( this );
425
426 mPlotItem = new QgsElevationProfilePlotItem( this );
427
428 // follow system color scheme by default
429 setBackgroundColor( QColor() );
430
431 mCrossHairsItem = new QgsElevationProfileCrossHairsItem( this, mPlotItem );
432 mCrossHairsItem->setZValue( 100 );
433 mCrossHairsItem->hide();
434
435 // updating the profile plot is deferred on a timer, so that we don't trigger it too often
436 mDeferredRegenerationTimer = new QTimer( this );
437 mDeferredRegenerationTimer->setSingleShot( true );
438 mDeferredRegenerationTimer->stop();
439 connect( mDeferredRegenerationTimer, &QTimer::timeout, this, &QgsElevationProfileCanvas::startDeferredRegeneration );
440
441 mDeferredRedrawTimer = new QTimer( this );
442 mDeferredRedrawTimer->setSingleShot( true );
443 mDeferredRedrawTimer->stop();
444 connect( mDeferredRedrawTimer, &QTimer::timeout, this, &QgsElevationProfileCanvas::startDeferredRedraw );
445
446 connect( QgsApplication::profileSourceRegistry(), &QgsProfileSourceRegistry::profileSourceRegistered, this, &QgsElevationProfileCanvas::setSourcesPrivate );
447 connect( QgsApplication::profileSourceRegistry(), &QgsProfileSourceRegistry::profileSourceUnregistered, this, &QgsElevationProfileCanvas::setSourcesPrivate );
448
449 setSourcesPrivate(); // Initialize with registered sources
450}
451
453{
454 if ( mCurrentJob )
455 {
456 mPlotItem->setRenderer( nullptr );
457 mCurrentJob->deleteLater();
458 mCurrentJob = nullptr;
459 }
460}
461
463{
464 if ( mCurrentJob )
465 {
466 mPlotItem->setRenderer( nullptr );
467 disconnect( mCurrentJob, &QgsProfilePlotRenderer::generationFinished, this, &QgsElevationProfileCanvas::generationFinished );
468 mCurrentJob->cancelGeneration();
469 mCurrentJob->deleteLater();
470 mCurrentJob = nullptr;
471 }
472}
473
475{
476 const double dxPercent = dx / mPlotItem->plotArea().width();
477 const double dyPercent = dy / mPlotItem->plotArea().height();
478
479 // these look backwards, but we are dragging the paper, not the view!
480 const double dxPlot = -dxPercent * ( mPlotItem->xMaximum() - mPlotItem->xMinimum() );
481 const double dyPlot = dyPercent * ( mPlotItem->yMaximum() - mPlotItem->yMinimum() );
482
483 // no need to handle axis scale lock here, we aren't changing scales
484 mPlotItem->setXMinimum( mPlotItem->xMinimum() + dxPlot );
485 mPlotItem->setXMaximum( mPlotItem->xMaximum() + dxPlot );
486 mPlotItem->setYMinimum( mPlotItem->yMinimum() + dyPlot );
487 mPlotItem->setYMaximum( mPlotItem->yMaximum() + dyPlot );
488
489 refineResults();
490
491 mPlotItem->updatePlot();
492 emit plotAreaChanged();
493}
494
496{
497 if ( !mPlotItem->plotArea().contains( x, y ) )
498 return;
499
500 const double newCenterX = mPlotItem->xMinimum() + ( x - mPlotItem->plotArea().left() ) / mPlotItem->plotArea().width() * ( mPlotItem->xMaximum() - mPlotItem->xMinimum() );
501 const double newCenterY = mPlotItem->yMinimum() + ( mPlotItem->plotArea().bottom() - y ) / mPlotItem->plotArea().height() * ( mPlotItem->yMaximum() - mPlotItem->yMinimum() );
502
503 const double dxPlot = newCenterX - ( mPlotItem->xMaximum() + mPlotItem->xMinimum() ) * 0.5;
504 const double dyPlot = newCenterY - ( mPlotItem->yMaximum() + mPlotItem->yMinimum() ) * 0.5;
505
506 // no need to handle axis scale lock here, we aren't changing scales
507 mPlotItem->setXMinimum( mPlotItem->xMinimum() + dxPlot );
508 mPlotItem->setXMaximum( mPlotItem->xMaximum() + dxPlot );
509 mPlotItem->setYMinimum( mPlotItem->yMinimum() + dyPlot );
510 mPlotItem->setYMaximum( mPlotItem->yMaximum() + dyPlot );
511
512 refineResults();
513
514 mPlotItem->updatePlot();
515 emit plotAreaChanged();
516}
517
519{
520 scalePlot( factor, factor );
521 emit plotAreaChanged();
522}
523
524QgsProfileSnapContext QgsElevationProfileCanvas::snapContext() const
525{
526 const double toleranceInPixels = QFontMetrics( font() ).horizontalAdvance( ' ' );
527 const double xToleranceInPlotUnits = ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor / ( mPlotItem->plotArea().width() ) * toleranceInPixels;
528 const double yToleranceInPlotUnits = ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) / ( mPlotItem->plotArea().height() ) * toleranceInPixels;
529
530 QgsProfileSnapContext context;
531 context.maximumSurfaceDistanceDelta = 2 * xToleranceInPlotUnits;
532 context.maximumSurfaceElevationDelta = 10 * yToleranceInPlotUnits;
533 context.maximumPointDistanceDelta = 4 * xToleranceInPlotUnits;
534 context.maximumPointElevationDelta = 4 * yToleranceInPlotUnits;
535 context.displayRatioElevationVsDistance = ( ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) / ( mPlotItem->plotArea().height() ) )
536 / ( ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor / ( mPlotItem->plotArea().width() ) );
537
538 return context;
539}
540
541QgsProfileIdentifyContext QgsElevationProfileCanvas::identifyContext() const
542{
543 const double toleranceInPixels = QFontMetrics( font() ).horizontalAdvance( ' ' );
544 const double xToleranceInPlotUnits = ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor / ( mPlotItem->plotArea().width() ) * toleranceInPixels;
545 const double yToleranceInPlotUnits = ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) / ( mPlotItem->plotArea().height() ) * toleranceInPixels;
546
547 QgsProfileIdentifyContext context;
548 context.maximumSurfaceDistanceDelta = 2 * xToleranceInPlotUnits;
549 context.maximumSurfaceElevationDelta = 10 * yToleranceInPlotUnits;
550 context.maximumPointDistanceDelta = 4 * xToleranceInPlotUnits;
551 context.maximumPointElevationDelta = 4 * yToleranceInPlotUnits;
552 context.displayRatioElevationVsDistance = ( ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) / ( mPlotItem->plotArea().height() ) )
553 / ( ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor / ( mPlotItem->plotArea().width() ) );
554
555 context.project = mProject;
556
557 return context;
558}
559
560void QgsElevationProfileCanvas::setupLayerConnections( QgsMapLayer *layer, bool isDisconnect )
561{
562 if ( isDisconnect )
563 {
564 disconnect( layer->elevationProperties(), &QgsMapLayerElevationProperties::profileGenerationPropertyChanged, this, &QgsElevationProfileCanvas::onLayerProfileGenerationPropertyChanged );
565 disconnect( layer->elevationProperties(), &QgsMapLayerElevationProperties::profileRenderingPropertyChanged, this, &QgsElevationProfileCanvas::onLayerProfileRendererPropertyChanged );
566 disconnect( layer, &QgsMapLayer::dataChanged, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
567 }
568 else
569 {
570 connect( layer->elevationProperties(), &QgsMapLayerElevationProperties::profileGenerationPropertyChanged, this, &QgsElevationProfileCanvas::onLayerProfileGenerationPropertyChanged );
571 connect( layer->elevationProperties(), &QgsMapLayerElevationProperties::profileRenderingPropertyChanged, this, &QgsElevationProfileCanvas::onLayerProfileRendererPropertyChanged );
572 connect( layer, &QgsMapLayer::dataChanged, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
573 }
574
575 switch ( layer->type() )
576 {
578 {
579 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer );
580 if ( isDisconnect )
581 {
582 disconnect( vl, &QgsVectorLayer::featureAdded, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
583 disconnect( vl, &QgsVectorLayer::featureDeleted, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
584 disconnect( vl, &QgsVectorLayer::geometryChanged, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
585 disconnect( vl, &QgsVectorLayer::attributeValueChanged, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
586 }
587 else
588 {
589 connect( vl, &QgsVectorLayer::featureAdded, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
590 connect( vl, &QgsVectorLayer::featureDeleted, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
591 connect( vl, &QgsVectorLayer::geometryChanged, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
592 connect( vl, &QgsVectorLayer::attributeValueChanged, this, &QgsElevationProfileCanvas::regenerateResultsForLayer );
593 }
594 break;
595 }
604 break;
605 }
606}
607
608void QgsElevationProfileCanvas::adjustRangeForAxisScaleLock( double &xMinimum, double &xMaximum, double &yMinimum, double &yMaximum ) const
609{
610 // ensures that we always "zoom out" to match horizontal/vertical scales
611 const double horizontalScale = ( xMaximum - xMinimum ) / mPlotItem->plotArea().width();
612 const double verticalScale = ( yMaximum - yMinimum ) / mPlotItem->plotArea().height();
613
614 const double currentRatio = horizontalScale / verticalScale;
615
616 if ( currentRatio <= mLockedAxisScale )
617 {
618 const double height = horizontalScale * mPlotItem->plotArea().height() / mLockedAxisScale;
619 const double deltaHeight = ( yMaximum - yMinimum ) - height;
620 yMinimum += deltaHeight / 2;
621 yMaximum -= deltaHeight / 2;
622 }
623 else
624 {
625 const double width = verticalScale * mPlotItem->plotArea().width() * mLockedAxisScale;
626 const double deltaWidth = ( ( xMaximum - xMinimum ) - width );
627 xMinimum += deltaWidth / 2;
628 xMaximum -= deltaWidth / 2;
629 }
630}
631
633{
634 return mDistanceUnit;
635}
636
638{
639 mDistanceUnit = unit;
640 const double oldMin = mPlotItem->xMinimum() * mPlotItem->mXScaleFactor;
641 const double oldMax = mPlotItem->xMaximum() * mPlotItem->mXScaleFactor;
642 mPlotItem->mXScaleFactor = QgsUnitTypes::fromUnitToUnitFactor( mDistanceUnit, mCrs.mapUnits() );
643 mPlotItem->setXAxisUnits( mDistanceUnit );
644 mPlotItem->setXMinimum( oldMin / mPlotItem->mXScaleFactor );
645 mPlotItem->setXMaximum( oldMax / mPlotItem->mXScaleFactor );
646 mPlotItem->updatePlot();
647 emit scaleChanged();
648}
649
651{
652 if ( !color.isValid() )
653 {
654 QPalette customPalette = qApp->palette();
655 const QColor baseColor = qApp->palette().color( QPalette::ColorRole::Base );
656 const QColor windowColor = qApp->palette().color( QPalette::ColorRole::Window );
657 customPalette.setColor( QPalette::ColorRole::Base, windowColor );
658 customPalette.setColor( QPalette::ColorRole::Window, baseColor );
659 setPalette( customPalette );
660 scene()->setPalette( customPalette );
661 }
662 else
663 {
664 // build custom palette
665 const bool isDarkTheme = color.lightnessF() < 0.5;
666 QPalette customPalette = qApp->palette();
667 customPalette.setColor( QPalette::ColorRole::Window, color );
668 if ( isDarkTheme )
669 {
670 customPalette.setColor( QPalette::ColorRole::Text, QColor( 255, 255, 255 ) );
671 customPalette.setColor( QPalette::ColorRole::Base, color.lighter( 120 ) );
672 }
673 else
674 {
675 customPalette.setColor( QPalette::ColorRole::Text, QColor( 0, 0, 0 ) );
676 customPalette.setColor( QPalette::ColorRole::Base, color.darker( 120 ) );
677 }
678
679 setPalette( customPalette );
680 scene()->setPalette( customPalette );
681 }
682
683 updateChartFromPalette();
684}
685
687{
688 return mLockAxisScales;
689}
690
692{
693 mLockAxisScales = lock;
694 if ( mLockAxisScales )
695 {
696 double xMinimum = mPlotItem->xMinimum() * mPlotItem->mXScaleFactor;
697 double xMaximum = mPlotItem->xMaximum() * mPlotItem->mXScaleFactor;
698 double yMinimum = mPlotItem->yMinimum();
699 double yMaximum = mPlotItem->yMaximum();
700 adjustRangeForAxisScaleLock( xMinimum, xMaximum, yMinimum, yMaximum );
701 mPlotItem->setXMinimum( xMinimum / mPlotItem->mXScaleFactor );
702 mPlotItem->setXMaximum( xMaximum / mPlotItem->mXScaleFactor );
703 mPlotItem->setYMinimum( yMinimum );
704 mPlotItem->setYMaximum( yMaximum );
705
706 refineResults();
707 mPlotItem->updatePlot();
708 emit plotAreaChanged();
709 emit scaleChanged();
710 }
711}
712
714{
715 const double horizontalScale = ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor / mPlotItem->plotArea().width();
716 const double verticalScale = ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) / mPlotItem->plotArea().height();
717 return horizontalScale / verticalScale;
718}
719
721{
722 mLockedAxisScale = scale;
723
724 double xMinimum = mPlotItem->xMinimum() * mPlotItem->mXScaleFactor;
725 double xMaximum = mPlotItem->xMaximum() * mPlotItem->mXScaleFactor;
726 double yMinimum = mPlotItem->yMinimum();
727 double yMaximum = mPlotItem->yMaximum();
728 adjustRangeForAxisScaleLock( xMinimum, xMaximum, yMinimum, yMaximum );
729 mPlotItem->setXMinimum( xMinimum / mPlotItem->mXScaleFactor );
730 mPlotItem->setXMaximum( xMaximum / mPlotItem->mXScaleFactor );
731 mPlotItem->setYMinimum( yMinimum );
732 mPlotItem->setYMaximum( yMaximum );
733
734 refineResults();
735 mPlotItem->updatePlot();
736 emit plotAreaChanged();
737 emit scaleChanged();
738}
739
741{
742 if ( !mCurrentJob || !mSnappingEnabled )
743 return QgsPointXY();
744
745 const QgsProfilePoint plotPoint = canvasPointToPlotPoint( point );
746
747 const QgsProfileSnapResult snappedPoint = mCurrentJob->snapPoint( plotPoint, snapContext() );
748 if ( !snappedPoint.isValid() )
749 return QgsPointXY();
750
751 return plotPointToCanvasPoint( snappedPoint.snappedPoint );
752}
753
754void QgsElevationProfileCanvas::scalePlot( double xFactor, double yFactor )
755{
756 if ( mLockAxisScales )
757 yFactor = xFactor;
758
759 const double currentWidth = ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor;
760 const double currentHeight = mPlotItem->yMaximum() - mPlotItem->yMinimum();
761
762 const double newWidth = currentWidth / xFactor;
763 const double newHeight = currentHeight / yFactor;
764
765 const double currentCenterX = ( mPlotItem->xMinimum() + mPlotItem->xMaximum() ) * 0.5 * mPlotItem->mXScaleFactor;
766 const double currentCenterY = ( mPlotItem->yMinimum() + mPlotItem->yMaximum() ) * 0.5;
767
768 double xMinimum = currentCenterX - newWidth * 0.5;
769 double xMaximum = currentCenterX + newWidth * 0.5;
770 double yMinimum = currentCenterY - newHeight * 0.5;
771 double yMaximum = currentCenterY + newHeight * 0.5;
772 if ( mLockAxisScales )
773 {
774 adjustRangeForAxisScaleLock( xMinimum, xMaximum, yMinimum, yMaximum );
775 }
776
777 mPlotItem->setXMinimum( xMinimum / mPlotItem->mXScaleFactor );
778 mPlotItem->setXMaximum( xMaximum / mPlotItem->mXScaleFactor );
779 mPlotItem->setYMinimum( yMinimum );
780 mPlotItem->setYMaximum( yMaximum );
781
782 refineResults();
783 mPlotItem->updatePlot();
784 emit plotAreaChanged();
785 emit scaleChanged();
786}
787
789{
790 const QRectF intersected = rect.intersected( mPlotItem->plotArea() );
791
792 double minX = ( intersected.left() - mPlotItem->plotArea().left() ) / mPlotItem->plotArea().width() * ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor
793 + mPlotItem->xMinimum() * mPlotItem->mXScaleFactor;
794 double maxX = ( intersected.right() - mPlotItem->plotArea().left() ) / mPlotItem->plotArea().width() * ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor
795 + mPlotItem->xMinimum() * mPlotItem->mXScaleFactor;
796 double minY = ( mPlotItem->plotArea().bottom() - intersected.bottom() ) / mPlotItem->plotArea().height() * ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) + mPlotItem->yMinimum();
797 double maxY = ( mPlotItem->plotArea().bottom() - intersected.top() ) / mPlotItem->plotArea().height() * ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) + mPlotItem->yMinimum();
798
799 if ( mLockAxisScales )
800 {
801 adjustRangeForAxisScaleLock( minX, maxX, minY, maxY );
802 }
803
804 mPlotItem->setXMinimum( minX / mPlotItem->mXScaleFactor );
805 mPlotItem->setXMaximum( maxX / mPlotItem->mXScaleFactor );
806 mPlotItem->setYMinimum( minY );
807 mPlotItem->setYMaximum( maxY );
808
809 refineResults();
810 mPlotItem->updatePlot();
811 emit plotAreaChanged();
812 emit scaleChanged();
813}
814
816{
817 //get mouse wheel zoom behavior settings
818 double zoomFactor = QgsSettingsRegistryGui::settingsZoomFactor->value();
819 bool reverseZoom = QgsSettingsRegistryGui::settingsReverseWheelZoom->value();
820 bool zoomIn = reverseZoom ? event->angleDelta().y() < 0 : event->angleDelta().y() > 0;
821
822 // "Normal" mouse have an angle delta of 120, precision mouses provide data faster, in smaller steps
823 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * std::fabs( event->angleDelta().y() );
824
825 if ( event->modifiers() & Qt::ControlModifier )
826 {
827 //holding ctrl while wheel zooming results in a finer zoom
828 zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
829 }
830
831 //calculate zoom scale factor
832 double scaleFactor = ( zoomIn ? 1 / zoomFactor : zoomFactor );
833
834 QRectF viewportRect = mPlotItem->plotArea();
835
836 if ( viewportRect.contains( event->position() ) )
837 {
838 //adjust view center
839 const double oldCenterX = 0.5 * ( mPlotItem->xMaximum() + mPlotItem->xMinimum() );
840 const double oldCenterY = 0.5 * ( mPlotItem->yMaximum() + mPlotItem->yMinimum() );
841
842 const double eventPosX = ( event->position().x() - viewportRect.left() ) / viewportRect.width() * ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) + mPlotItem->xMinimum();
843 const double eventPosY = ( viewportRect.bottom() - event->position().y() ) / viewportRect.height() * ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) + mPlotItem->yMinimum();
844
845 const double newCenterX = eventPosX + ( ( oldCenterX - eventPosX ) * scaleFactor );
846 const double newCenterY = eventPosY + ( ( oldCenterY - eventPosY ) * scaleFactor );
847
848 const double dxPlot = newCenterX - ( mPlotItem->xMaximum() + mPlotItem->xMinimum() ) * 0.5;
849 const double dyPlot = newCenterY - ( mPlotItem->yMaximum() + mPlotItem->yMinimum() ) * 0.5;
850
851 // don't need to handle axis scale lock here, we are always changing axis by the same scale
852 mPlotItem->setXMinimum( mPlotItem->xMinimum() + dxPlot );
853 mPlotItem->setXMaximum( mPlotItem->xMaximum() + dxPlot );
854 mPlotItem->setYMinimum( mPlotItem->yMinimum() + dyPlot );
855 mPlotItem->setYMaximum( mPlotItem->yMaximum() + dyPlot );
856 }
857
858 //zoom plot
859 if ( zoomIn )
860 {
861 scalePlot( zoomFactor );
862 }
863 else
864 {
865 scalePlot( 1 / zoomFactor );
866 }
867 emit plotAreaChanged();
868 emit scaleChanged();
869}
870
872{
874 if ( e->isAccepted() )
875 {
876 mCrossHairsItem->hide();
877 return;
878 }
879
880 QgsProfilePoint plotPoint = canvasPointToPlotPoint( e->pos() );
881 if ( mCurrentJob && mSnappingEnabled && !plotPoint.isEmpty() )
882 {
883 const QgsProfileSnapResult snapResult = mCurrentJob->snapPoint( plotPoint, snapContext() );
884 if ( snapResult.isValid() )
885 plotPoint = snapResult.snappedPoint;
886 }
887
888 if ( plotPoint.isEmpty() )
889 {
890 mCrossHairsItem->hide();
891 }
892 else
893 {
894 mCrossHairsItem->setPoint( plotPoint );
895 mCrossHairsItem->show();
896 }
897 emit canvasPointHovered( e->pos(), plotPoint );
898}
899
901{
902 return mPlotItem->plotArea();
903}
904
906{
907 if ( !mProject || !profileCurve() )
908 return;
909
910 cancelJobs();
911
912 QgsProfileRequest request( profileCurve()->clone() );
913 request.setCrs( mCrs );
914 request.setTolerance( mTolerance );
915 request.setTransformContext( mProject->transformContext() );
916 request.setTerrainProvider( mProject->elevationProperties()->terrainProvider() ? mProject->elevationProperties()->terrainProvider()->clone() : nullptr );
917 QgsExpressionContext context;
920 request.setExpressionContext( context );
921
922 QList< QgsAbstractProfileSource *> sourcesToRender = sources();
923 std::reverse( sourcesToRender.begin(), sourcesToRender.end() ); // sources are rendered from bottom to top
924
925 mCurrentJob = new QgsProfilePlotRenderer( sourcesToRender, request );
926 connect( mCurrentJob, &QgsProfilePlotRenderer::generationFinished, this, &QgsElevationProfileCanvas::generationFinished );
927
928 QgsProfileGenerationContext generationContext;
929 generationContext.setDpi( mScreenHelper->screenDpi() );
930 generationContext.setMaximumErrorMapUnits( MAX_ERROR_PIXELS * ( mProfileCurve->length() ) / mPlotItem->plotArea().width() );
931 generationContext.setMapUnitsPerDistancePixel( mProfileCurve->length() / mPlotItem->plotArea().width() );
932 mCurrentJob->setContext( generationContext );
933
934 if ( mSubsectionsSymbol )
935 {
936 mCurrentJob->setSubsectionsSymbol( mSubsectionsSymbol->clone() );
937 }
938
939 mCurrentJob->startGeneration();
940 mPlotItem->setRenderer( mCurrentJob );
941
942 emit activeJobCountChanged( 1 );
943}
944
946{
947 mZoomFullWhenJobFinished = true;
948}
949
950void QgsElevationProfileCanvas::generationFinished()
951{
952 if ( !mCurrentJob )
953 return;
954
955 emit activeJobCountChanged( 0 );
956
957 if ( mZoomFullWhenJobFinished )
958 {
959 // we only zoom full for the initial generation
960 mZoomFullWhenJobFinished = false;
961 zoomFull();
962 }
963 else
964 {
965 // here we should invalidate cached results only for the layers which have been refined
966
967 // and if no layers are being refined, don't invalidate anything
968
969 mPlotItem->updatePlot();
970 }
971
972 if ( mForceRegenerationAfterCurrentJobCompletes )
973 {
974 mForceRegenerationAfterCurrentJobCompletes = false;
975 mCurrentJob->invalidateAllRefinableSources();
976 scheduleDeferredRegeneration();
977 }
978}
979
980void QgsElevationProfileCanvas::onLayerProfileGenerationPropertyChanged()
981{
982 // TODO -- handle nicely when existing job is in progress
983 if ( !mCurrentJob || mCurrentJob->isActive() )
984 return;
985
986 QgsMapLayerElevationProperties *properties = qobject_cast<QgsMapLayerElevationProperties *>( sender() );
987 if ( !properties )
988 return;
989
990 if ( QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( properties->parent() ) )
991 {
992 if ( QgsAbstractProfileSource *source = layer->profileSource() )
993 {
994 if ( mCurrentJob->invalidateResults( source ) )
995 scheduleDeferredRegeneration();
996 }
997 }
998}
999
1000void QgsElevationProfileCanvas::onLayerProfileRendererPropertyChanged()
1001{
1002 // TODO -- handle nicely when existing job is in progress
1003 if ( !mCurrentJob || mCurrentJob->isActive() )
1004 return;
1005
1006 QgsMapLayerElevationProperties *properties = qobject_cast<QgsMapLayerElevationProperties *>( sender() );
1007 if ( !properties )
1008 return;
1009
1010 if ( QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( properties->parent() ) )
1011 {
1012 if ( QgsAbstractProfileSource *source = layer->profileSource() )
1013 {
1014 mCurrentJob->replaceSource( source );
1015 }
1016 if ( mPlotItem->redrawResults( layer->id() ) )
1017 scheduleDeferredRedraw();
1018 }
1019}
1020
1021void QgsElevationProfileCanvas::regenerateResultsForLayer()
1022{
1023 if ( !mCurrentJob )
1024 return;
1025
1026 if ( QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() ) )
1027 {
1028 if ( QgsAbstractProfileSource *source = layer->profileSource() )
1029 {
1030 if ( mCurrentJob->invalidateResults( source ) )
1031 scheduleDeferredRegeneration();
1032 }
1033 }
1034}
1035
1036void QgsElevationProfileCanvas::scheduleDeferredRegeneration()
1037{
1038 if ( !mDeferredRegenerationScheduled )
1039 {
1040 mDeferredRegenerationTimer->start( 1 );
1041 mDeferredRegenerationScheduled = true;
1042 }
1043}
1044
1045void QgsElevationProfileCanvas::scheduleDeferredRedraw()
1046{
1047 if ( !mDeferredRedrawScheduled )
1048 {
1049 mDeferredRedrawTimer->start( 1 );
1050 mDeferredRedrawScheduled = true;
1051 }
1052}
1053
1054void QgsElevationProfileCanvas::startDeferredRegeneration()
1055{
1056 if ( mCurrentJob && !mCurrentJob->isActive() )
1057 {
1058 emit activeJobCountChanged( 1 );
1059 mCurrentJob->regenerateInvalidatedResults();
1060 }
1061 else if ( mCurrentJob )
1062 {
1063 mForceRegenerationAfterCurrentJobCompletes = true;
1064 }
1065
1066 mDeferredRegenerationScheduled = false;
1067}
1068
1069void QgsElevationProfileCanvas::startDeferredRedraw()
1070{
1071 mPlotItem->update();
1072 mDeferredRedrawScheduled = false;
1073}
1074
1075void QgsElevationProfileCanvas::refineResults()
1076{
1077 if ( mCurrentJob )
1078 {
1079 QgsProfileGenerationContext context;
1080 context.setDpi( mScreenHelper->screenDpi() );
1081 const double plotDistanceRange = ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor;
1082 const double plotElevationRange = mPlotItem->yMaximum() - mPlotItem->yMinimum();
1083 const double plotDistanceUnitsPerPixel = plotDistanceRange / mPlotItem->plotArea().width();
1084
1085 // we round the actual desired map error down to just one significant figure, to avoid tiny differences
1086 // as the plot is panned
1087 const double targetMaxErrorInMapUnits = MAX_ERROR_PIXELS * plotDistanceUnitsPerPixel;
1088 const double factor = std::pow( 10.0, 1 - std::ceil( std::log10( std::fabs( targetMaxErrorInMapUnits ) ) ) );
1089 const double roundedErrorInMapUnits = std::floor( targetMaxErrorInMapUnits * factor ) / factor;
1090 context.setMaximumErrorMapUnits( roundedErrorInMapUnits );
1091
1092 context.setMapUnitsPerDistancePixel( plotDistanceUnitsPerPixel );
1093
1094 // for similar reasons we round the minimum distance off to multiples of the maximum error in map units
1095 const double distanceMin = std::floor( ( mPlotItem->xMinimum() * mPlotItem->mXScaleFactor - plotDistanceRange * 0.05 ) / context.maximumErrorMapUnits() ) * context.maximumErrorMapUnits();
1096 context.setDistanceRange( QgsDoubleRange( std::max( 0.0, distanceMin ), mPlotItem->xMaximum() * mPlotItem->mXScaleFactor + plotDistanceRange * 0.05 ) );
1097
1098 context.setElevationRange( QgsDoubleRange( mPlotItem->yMinimum() - plotElevationRange * 0.05, mPlotItem->yMaximum() + plotElevationRange * 0.05 ) );
1099 mCurrentJob->setContext( context );
1100 }
1101 scheduleDeferredRegeneration();
1102}
1103
1104void QgsElevationProfileCanvas::updateChartFromPalette()
1105{
1106 const QPalette chartPalette = palette();
1107 setBackgroundBrush( QBrush( chartPalette.color( QPalette::ColorRole::Base ) ) );
1108 {
1109 QgsTextFormat textFormat = mPlotItem->xAxis().textFormat();
1110 textFormat.setColor( chartPalette.color( QPalette::ColorGroup::Active, QPalette::Text ) );
1111 mPlotItem->xAxis().setTextFormat( textFormat );
1112 mPlotItem->yAxis().setTextFormat( textFormat );
1113 }
1114 {
1115 std::unique_ptr<QgsFillSymbol> chartFill( mPlotItem->chartBackgroundSymbol()->clone() );
1116 chartFill->setColor( chartPalette.color( QPalette::ColorGroup::Active, QPalette::ColorRole::Window ) );
1117 mPlotItem->setChartBackgroundSymbol( chartFill.release() );
1118 }
1119 {
1120 std::unique_ptr<QgsFillSymbol> chartBorder( mPlotItem->chartBorderSymbol()->clone() );
1121 chartBorder->setColor( chartPalette.color( QPalette::ColorGroup::Active, QPalette::ColorRole::Text ) );
1122 mPlotItem->setChartBorderSymbol( chartBorder.release() );
1123 }
1124 {
1125 std::unique_ptr<QgsLineSymbol> chartMajorSymbol( mPlotItem->xAxis().gridMajorSymbol()->clone() );
1126 QColor c = chartPalette.color( QPalette::ColorGroup::Active, QPalette::ColorRole::Text );
1127 c.setAlpha( 150 );
1128 chartMajorSymbol->setColor( c );
1129 mPlotItem->xAxis().setGridMajorSymbol( chartMajorSymbol->clone() );
1130 mPlotItem->yAxis().setGridMajorSymbol( chartMajorSymbol.release() );
1131 }
1132 {
1133 std::unique_ptr<QgsLineSymbol> chartMinorSymbol( mPlotItem->xAxis().gridMinorSymbol()->clone() );
1134 QColor c = chartPalette.color( QPalette::ColorGroup::Active, QPalette::ColorRole::Text );
1135 c.setAlpha( 50 );
1136 chartMinorSymbol->setColor( c );
1137 mPlotItem->xAxis().setGridMinorSymbol( chartMinorSymbol->clone() );
1138 mPlotItem->yAxis().setGridMinorSymbol( chartMinorSymbol.release() );
1139 }
1140 mPlotItem->updatePlot();
1141}
1142
1144{
1145 if ( !mPlotItem->plotArea().contains( point.x(), point.y() ) )
1146 return QgsProfilePoint();
1147
1148 return mPlotItem->canvasPointToPlotPoint( point );
1149}
1150
1152{
1153 return mPlotItem->plotPointToCanvasPoint( point );
1154}
1155
1157{
1158 mProject = project;
1159 mPlotItem->mProject = project;
1160}
1161
1166
1168{
1169 mProfileCurve.reset( curve );
1170}
1171
1173{
1174 return mProfileCurve.get();
1175}
1176
1178{
1179 mTolerance = tolerance;
1180}
1181
1186
1187void QgsElevationProfileCanvas::setLayers( const QList<QgsMapLayer *> &layers )
1188{
1189 for ( QgsMapLayer *layer : std::as_const( mLayers ) )
1190 {
1191 setupLayerConnections( layer, true );
1192 }
1193
1194 // filter list, removing null layers and invalid layers
1195 auto filteredList = layers;
1196 filteredList.erase( std::remove_if( filteredList.begin(), filteredList.end(), []( QgsMapLayer *layer ) { return !layer || !layer->isValid(); } ), filteredList.end() );
1197
1198 mLayers = _qgis_listRawToQPointer( filteredList );
1199 for ( QgsMapLayer *layer : std::as_const( mLayers ) )
1200 {
1201 setupLayerConnections( layer, false );
1202 }
1203}
1204
1205QList<QgsMapLayer *> QgsElevationProfileCanvas::layers() const
1206{
1207 return _qgis_listQPointerToRaw( mLayers );
1208}
1209
1210void QgsElevationProfileCanvas::setSources( const QList< std::variant< QgsMapLayer *, QgsAbstractProfileSource * > > &sources )
1211{
1212 mSources.clear();
1213 mSources.reserve( sources.count() );
1214
1215 for ( const auto &source : sources )
1216 {
1217 if ( auto *layer = std::get_if< QgsMapLayer * >( &source ) )
1218 {
1219 if ( ( *layer )->profileSource() )
1220 {
1221 mSources << QgsWeakMapLayerPointer( *layer );
1222 }
1223 }
1224 else if ( auto *profileSource = std::get_if< QgsAbstractProfileSource * >( &source ) )
1225 {
1226 if ( QgsApplication::profileSourceRegistry()->findSourceById( ( *profileSource )->profileSourceId() ) )
1227 {
1228 mSources << *profileSource;
1229 }
1230 else
1231 {
1232 QgsMessageLog::logMessage( tr( "Could not find profile source with id '%1' in the registry. Skipping..." ).arg( ( *profileSource )->profileSourceId() ) );
1233 }
1234 }
1235 }
1236}
1237
1238QList<QgsAbstractProfileSource *> QgsElevationProfileCanvas::sources() const
1239{
1240 if ( mSources.isEmpty() && !mLayers.isEmpty() )
1241 {
1242 // Legacy: If we have layers, extract their sources and return them.
1243 // We don't set mSources here, because we want the previous check to
1244 // continue failing if only layers are set.
1245 // TODO: Remove in QGIS 5.0.
1246 QList< QgsAbstractProfileSource * > sources;
1247 const QList<QgsMapLayer *> layersToGenerate = layers();
1248 sources.reserve( layersToGenerate.size() );
1249
1250 for ( QgsMapLayer *layer : layersToGenerate )
1251 {
1252 if ( QgsAbstractProfileSource *source = layer->profileSource() )
1253 sources << source;
1254 }
1255
1256 // More legacy: canvas layers are in the same direction as the renderer
1257 // expects, but since we reverse sources() (i.e., layers) before passing
1258 // them to the renderer, then we need to reverse them here first.
1259 std::reverse( sources.begin(), sources.end() );
1260 return sources;
1261 }
1262
1263 QList< QgsAbstractProfileSource * > sources;
1264 sources.reserve( mSources.count() );
1265 for ( const auto &source : mSources )
1266 {
1267 if ( const QgsWeakMapLayerPointer *weakLayerPointer = std::get_if< QgsWeakMapLayerPointer >( &source ) )
1268 {
1269 if ( QgsMapLayer *layer = weakLayerPointer->data() )
1270 {
1271 sources << layer->profileSource();
1272 }
1273 }
1274 else if ( auto *profileSource = std::get_if< QgsAbstractProfileSource * >( &source ) )
1275 {
1276 if ( QgsApplication::profileSourceRegistry()->findSourceById( ( *profileSource )->profileSourceId() ) )
1277 {
1278 sources << *profileSource;
1279 }
1280 else
1281 {
1282 QgsMessageLog::logMessage( tr( "Could not find profile source with id '%1' in the registry. Skipping..." ).arg( ( *profileSource )->profileSourceId() ) );
1283 }
1284 }
1285 }
1286
1287 return sources;
1288}
1289
1290QList< std::variant< QgsMapLayer *, QgsAbstractProfileSource * > > QgsElevationProfileCanvas::rawSources() const
1291{
1292 QList< std::variant< QgsMapLayer *, QgsAbstractProfileSource * > > sources;
1293 sources.reserve( mSources.count() );
1294 for ( const auto &source : mSources )
1295 {
1296 if ( const QgsWeakMapLayerPointer *weakLayerPointer = std::get_if< QgsWeakMapLayerPointer >( &source ) )
1297 {
1298 if ( QgsMapLayer *layer = weakLayerPointer->data() )
1299 {
1300 sources << layer;
1301 }
1302 }
1303 else if ( auto *profileSource = std::get_if< QgsAbstractProfileSource * >( &source ) )
1304 {
1305 if ( QgsApplication::profileSourceRegistry()->findSourceById( ( *profileSource )->profileSourceId() ) )
1306 {
1307 sources << *profileSource;
1308 }
1309 else
1310 {
1311 QgsMessageLog::logMessage( tr( "Could not find profile source with id '%1' in the registry. Skipping..." ).arg( ( *profileSource )->profileSourceId() ) );
1312 }
1313 }
1314 }
1315
1316 return sources;
1317}
1318
1320{
1322
1323 if ( mLockAxisScales )
1324 {
1325 double xMinimum = mPlotItem->xMinimum();
1326 double xMaximum = mPlotItem->xMaximum();
1327 double yMinimum = mPlotItem->yMinimum();
1328 double yMaximum = mPlotItem->yMaximum();
1329 adjustRangeForAxisScaleLock( xMinimum, xMaximum, yMinimum, yMaximum );
1330 mPlotItem->setXMinimum( xMinimum );
1331 mPlotItem->setXMaximum( xMaximum );
1332 mPlotItem->setYMinimum( yMinimum );
1333 mPlotItem->setYMaximum( yMaximum );
1334 }
1335
1336 mPlotItem->updateRect();
1337 mCrossHairsItem->updateRect();
1338
1339 emit scaleChanged();
1340}
1341
1343{
1344 QgsPlotCanvas::paintEvent( event );
1345
1346 if ( !mFirstDrawOccurred )
1347 {
1348 // on first show we need to update the visible rect of the plot. (Not sure why this doesn't work in showEvent, but it doesn't).
1349 mFirstDrawOccurred = true;
1350 mPlotItem->updateRect();
1351 mCrossHairsItem->updateRect();
1352 }
1353}
1354
1356{
1357 if ( !mPlotItem->plotArea().contains( point.x(), point.y() ) )
1358 return QgsPoint();
1359
1360 if ( !mProfileCurve )
1361 return QgsPoint();
1362
1363 const double dx = point.x() - mPlotItem->plotArea().left();
1364
1365 const double distanceAlongPlotPercent = dx / mPlotItem->plotArea().width();
1366 double distanceAlongCurveLength = distanceAlongPlotPercent * ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor + mPlotItem->xMinimum() * mPlotItem->mXScaleFactor;
1367
1368 std::unique_ptr<QgsPoint> mapXyPoint( mProfileCurve->interpolatePoint( distanceAlongCurveLength ) );
1369 if ( !mapXyPoint )
1370 return QgsPoint();
1371
1372 const double mapZ = ( mPlotItem->yMaximum() - mPlotItem->yMinimum() ) / ( mPlotItem->plotArea().height() ) * ( mPlotItem->plotArea().bottom() - point.y() ) + mPlotItem->yMinimum();
1373
1374 return QgsPoint( mapXyPoint->x(), mapXyPoint->y(), mapZ );
1375}
1376
1378{
1379 if ( !mProfileCurve )
1380 return QgsPointXY();
1381
1382 QgsGeos geos( mProfileCurve.get() );
1383 QString error;
1384 const double distanceAlongCurve = geos.lineLocatePoint( point, &error );
1385
1386 const double distanceAlongCurveOnPlot = distanceAlongCurve - mPlotItem->xMinimum() * mPlotItem->mXScaleFactor;
1387 const double distanceAlongCurvePercent = distanceAlongCurveOnPlot / ( ( mPlotItem->xMaximum() - mPlotItem->xMinimum() ) * mPlotItem->mXScaleFactor );
1388 const double distanceAlongPlotRect = distanceAlongCurvePercent * mPlotItem->plotArea().width();
1389
1390 const double canvasX = mPlotItem->plotArea().left() + distanceAlongPlotRect;
1391
1392 double canvasY = 0;
1393 if ( std::isnan( point.z() ) || point.z() < mPlotItem->yMinimum() )
1394 {
1395 canvasY = mPlotItem->plotArea().top();
1396 }
1397 else if ( point.z() > mPlotItem->yMaximum() )
1398 {
1399 canvasY = mPlotItem->plotArea().bottom();
1400 }
1401 else
1402 {
1403 const double yPercent = ( point.z() - mPlotItem->yMinimum() ) / ( mPlotItem->yMaximum() - mPlotItem->yMinimum() );
1404 canvasY = mPlotItem->plotArea().bottom() - mPlotItem->plotArea().height() * yPercent;
1405 }
1406
1407 return QgsPointXY( canvasX, canvasY );
1408}
1409
1411{
1412 if ( !mCurrentJob )
1413 return;
1414
1415 const QgsDoubleRange zRange = mCurrentJob->zRange();
1416
1417 double yMinimum = 0;
1418 double yMaximum = 0;
1419
1420 if ( zRange.upper() < zRange.lower() )
1421 {
1422 // invalid range, e.g. no features found in plot!
1423 yMinimum = 0;
1424 yMaximum = 10;
1425 }
1426 else if ( qgsDoubleNear( zRange.lower(), zRange.upper(), 0.0000001 ) )
1427 {
1428 // corner case ... a zero height plot! Just pick an arbitrary +/- 5 height range.
1429 yMinimum = zRange.lower() - 5;
1430 yMaximum = zRange.lower() + 5;
1431 }
1432 else
1433 {
1434 // add 5% margin to height range
1435 const double margin = ( zRange.upper() - zRange.lower() ) * 0.05;
1436 yMinimum = zRange.lower() - margin;
1437 yMaximum = zRange.upper() + margin;
1438 }
1439
1440 const double profileLength = profileCurve()->length();
1441 double xMinimum = 0;
1442 // just 2% margin to max distance -- any more is overkill and wasted space
1443 double xMaximum = profileLength * 1.02;
1444
1445 if ( mLockAxisScales )
1446 {
1447 adjustRangeForAxisScaleLock( xMinimum, xMaximum, yMinimum, yMaximum );
1448 }
1449
1450 mPlotItem->setXMinimum( xMinimum / mPlotItem->mXScaleFactor );
1451 mPlotItem->setXMaximum( xMaximum / mPlotItem->mXScaleFactor );
1452 mPlotItem->setYMinimum( yMinimum );
1453 mPlotItem->setYMaximum( yMaximum );
1454
1455 refineResults();
1456 mPlotItem->updatePlot();
1457 emit plotAreaChanged();
1458 emit scaleChanged();
1459}
1460
1461void QgsElevationProfileCanvas::setVisiblePlotRange( double minimumDistance, double maximumDistance, double minimumElevation, double maximumElevation )
1462{
1463 if ( mLockAxisScales )
1464 {
1465 adjustRangeForAxisScaleLock( minimumDistance, maximumDistance, minimumElevation, maximumElevation );
1466 }
1467
1468 mPlotItem->setYMinimum( minimumElevation );
1469 mPlotItem->setYMaximum( maximumElevation );
1470 mPlotItem->setXMinimum( minimumDistance / mPlotItem->mXScaleFactor );
1471 mPlotItem->setXMaximum( maximumDistance / mPlotItem->mXScaleFactor );
1472 refineResults();
1473 mPlotItem->updatePlot();
1474 emit plotAreaChanged();
1475 emit scaleChanged();
1476}
1477
1479{
1480 return QgsDoubleRange( mPlotItem->xMinimum() * mPlotItem->mXScaleFactor, mPlotItem->xMaximum() * mPlotItem->mXScaleFactor );
1481}
1482
1484{
1485 return QgsDoubleRange( mPlotItem->yMinimum(), mPlotItem->yMaximum() );
1486}
1487
1489{
1490 if ( mCurrentJob )
1491 return mCurrentJob->zRange();
1492 return QgsDoubleRange();
1493}
1494
1496{
1497 return *mPlotItem;
1498}
1499
1501class QgsElevationProfilePlot : public Qgs2DXyPlot
1502{
1503 public:
1504 QgsElevationProfilePlot( QgsProfilePlotRenderer *renderer )
1505 : mRenderer( renderer )
1506 {}
1507
1508 void renderContent( QgsRenderContext &rc, QgsPlotRenderContext &, const QRectF &plotArea, const QgsPlotData & ) override
1509 {
1510 if ( !mRenderer )
1511 return;
1512
1513 rc.painter()->translate( plotArea.left(), plotArea.top() );
1514 mRenderer->render( rc, plotArea.width(), plotArea.height(), xMinimum() * mXScale, xMaximum() * mXScale, yMinimum(), yMaximum() );
1515 rc.painter()->translate( -plotArea.left(), -plotArea.top() );
1516 }
1517
1518 double mXScale = 1;
1519
1520 private:
1521 QgsProfilePlotRenderer *mRenderer = nullptr;
1522};
1524
1525void QgsElevationProfileCanvas::render( QgsRenderContext &context, double width, double height, const Qgs2DXyPlot &plotSettings )
1526{
1527 if ( !mCurrentJob )
1528 return;
1529
1532
1533 QgsElevationProfilePlot profilePlot( mCurrentJob );
1534
1535 // quick and nasty way to transfer settings from another plot class -- in future we probably want to improve this, but let's let the API settle first...
1536 QDomDocument doc;
1537 QDomElement elem = doc.createElement( u"plot"_s );
1538 QgsReadWriteContext rwContext;
1539 plotSettings.writeXml( elem, doc, rwContext );
1540 profilePlot.readXml( elem, rwContext );
1541
1542 profilePlot.mXScale = mPlotItem->mXScaleFactor;
1543 profilePlot.xAxis().setLabelSuffix( mPlotItem->xAxis().labelSuffix() );
1544 profilePlot.xAxis().setLabelSuffixPlacement( mPlotItem->xAxis().labelSuffixPlacement() );
1545
1546 profilePlot.setSize( QSizeF( width, height ) );
1547 QgsPlotRenderContext plotContext;
1548 profilePlot.render( context, plotContext );
1549}
1550
1551QVector<QgsProfileIdentifyResults> QgsElevationProfileCanvas::identify( QPointF point )
1552{
1553 if ( !mCurrentJob )
1554 return {};
1555
1556 const QgsProfilePoint plotPoint = canvasPointToPlotPoint( point );
1557
1558 return mCurrentJob->identify( plotPoint, identifyContext() );
1559}
1560
1561QVector<QgsProfileIdentifyResults> QgsElevationProfileCanvas::identify( const QRectF &rect )
1562{
1563 if ( !mCurrentJob )
1564 return {};
1565
1566 const QgsProfilePoint topLeftPlotPoint = canvasPointToPlotPoint( rect.topLeft() );
1567 const QgsProfilePoint bottomRightPlotPoint = canvasPointToPlotPoint( rect.bottomRight() );
1568
1569 double distance1 = topLeftPlotPoint.distance();
1570 double distance2 = bottomRightPlotPoint.distance();
1571 if ( distance2 < distance1 )
1572 std::swap( distance1, distance2 );
1573
1574 double elevation1 = topLeftPlotPoint.elevation();
1575 double elevation2 = bottomRightPlotPoint.elevation();
1576 if ( elevation2 < elevation1 )
1577 std::swap( elevation1, elevation2 );
1578
1579 return mCurrentJob->identify( QgsDoubleRange( distance1, distance2 ), QgsDoubleRange( elevation1, elevation2 ), identifyContext() );
1580}
1581
1583{
1584 setProfileCurve( nullptr );
1585 cancelJobs();
1586 mPlotItem->updatePlot();
1587}
1588
1590{
1591 mSnappingEnabled = enabled;
1592}
1593
1595{
1596 mSubsectionsSymbol.reset( symbol );
1597 std::unique_ptr<QgsLineSymbol> plotItemSymbol( mSubsectionsSymbol ? mSubsectionsSymbol->clone() : nullptr );
1598 mPlotItem->setSubsectionsSymbol( plotItemSymbol.release() );
1599}
1600
1601void QgsElevationProfileCanvas::setSourcesPrivate()
1602{
1603 mSources.clear();
1604 mSources.reserve( QgsApplication::profileSourceRegistry()->profileSources().count() );
1605 for ( QgsAbstractProfileSource *source : QgsApplication::profileSourceRegistry()->profileSources() )
1606 mSources << source;
1607}
@ FirstAndLastLabels
Place suffix after the first and last label values only.
Definition qgis.h:3573
DistanceUnit
Units of distance.
Definition qgis.h:5580
@ YardsBritishSears1922Truncated
British yards (Sears 1922 truncated).
Definition qgis.h:5620
@ Feet
Imperial feet.
Definition qgis.h:5583
@ MilesUSSurvey
US Survey miles.
Definition qgis.h:5627
@ LinksBritishSears1922
British links (Sears 1922).
Definition qgis.h:5615
@ YardsBritishBenoit1895A
British yards (Benoit 1895 A).
Definition qgis.h:5618
@ LinksBritishBenoit1895A
British links (Benoit 1895 A).
Definition qgis.h:5612
@ Centimeters
Centimeters.
Definition qgis.h:5588
@ YardsIndian1975
Indian yards (1975).
Definition qgis.h:5626
@ FeetUSSurvey
US Survey feet.
Definition qgis.h:5610
@ Millimeters
Millimeters.
Definition qgis.h:5589
@ FeetBritishSears1922
British feet (Sears 1922).
Definition qgis.h:5603
@ YardsClarkes
Clarke's yards.
Definition qgis.h:5622
@ YardsIndian
Indian yards.
Definition qgis.h:5623
@ FeetBritishBenoit1895B
British feet (Benoit 1895 B).
Definition qgis.h:5601
@ Miles
Terrestrial miles.
Definition qgis.h:5586
@ LinksUSSurvey
US Survey links.
Definition qgis.h:5617
@ Meters
Meters.
Definition qgis.h:5581
@ ChainsUSSurvey
US Survey chains.
Definition qgis.h:5597
@ FeetClarkes
Clarke's feet.
Definition qgis.h:5604
@ Unknown
Unknown distance unit.
Definition qgis.h:5630
@ Yards
Imperial yards.
Definition qgis.h:5585
@ FeetBritish1936
British feet (1936).
Definition qgis.h:5599
@ FeetIndian1962
Indian feet (1962).
Definition qgis.h:5608
@ YardsBritishSears1922
British yards (Sears 1922).
Definition qgis.h:5621
@ FeetIndian1937
Indian feet (1937).
Definition qgis.h:5607
@ YardsIndian1937
Indian yards (1937).
Definition qgis.h:5624
@ Degrees
Degrees, for planar geographic CRS distance measurements.
Definition qgis.h:5587
@ ChainsBritishBenoit1895B
British chains (Benoit 1895 B).
Definition qgis.h:5593
@ LinksBritishSears1922Truncated
British links (Sears 1922 truncated).
Definition qgis.h:5614
@ ChainsBritishBenoit1895A
British chains (Benoit 1895 A).
Definition qgis.h:5592
@ YardsBritishBenoit1895B
British yards (Benoit 1895 B).
Definition qgis.h:5619
@ FeetBritish1865
British feet (1865).
Definition qgis.h:5598
@ YardsIndian1962
Indian yards (1962).
Definition qgis.h:5625
@ FeetBritishSears1922Truncated
British feet (Sears 1922 truncated).
Definition qgis.h:5602
@ MetersGermanLegal
German legal meter.
Definition qgis.h:5629
@ LinksBritishBenoit1895B
British links (Benoit 1895 B).
Definition qgis.h:5613
@ ChainsInternational
International chains.
Definition qgis.h:5591
@ Inches
Inches.
Definition qgis.h:5590
@ Fathoms
Fathoms.
Definition qgis.h:5628
@ LinksInternational
International links.
Definition qgis.h:5611
@ ChainsBritishSears1922Truncated
British chains (Sears 1922 truncated).
Definition qgis.h:5594
@ FeetIndian
Indian (geodetic) feet.
Definition qgis.h:5606
@ NauticalMiles
Nautical miles.
Definition qgis.h:5584
@ ChainsClarkes
Clarke's chains.
Definition qgis.h:5596
@ LinksClarkes
Clarke's links.
Definition qgis.h:5616
@ ChainsBritishSears1922
British chains (Sears 1922).
Definition qgis.h:5595
@ Kilometers
Kilometers.
Definition qgis.h:5582
@ FeetIndian1975
Indian feet (1975).
Definition qgis.h:5609
@ FeetGoldCoast
Gold Coast feet.
Definition qgis.h:5605
@ FeetBritishBenoit1895A
British feet (Benoit 1895 A).
Definition qgis.h:5600
@ Group
Composite group layer. Added in QGIS 3.24.
Definition qgis.h:214
@ Plugin
Plugin based layer.
Definition qgis.h:209
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
Definition qgis.h:215
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
Definition qgis.h:212
@ Vector
Vector layer.
Definition qgis.h:207
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
Definition qgis.h:211
@ Mesh
Mesh layer. Added in QGIS 3.2.
Definition qgis.h:210
@ Raster
Raster layer.
Definition qgis.h:208
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
Definition qgis.h:213
virtual void renderContent(QgsRenderContext &context, QgsPlotRenderContext &plotContext, const QRectF &plotArea, const QgsPlotData &plotData=QgsPlotData())
Renders the plot content.
Definition qgsplot.cpp:310
void setSize(QSizeF size)
Sets the overall size of the plot (including titles and over components which sit outside the plot ar...
Definition qgsplot.cpp:320
Base class for 2-dimensional plot/chart/graphs with an X and Y axes.
Definition qgsplot.h:687
double yMaximum() const
Returns the maximum value of the y axis.
Definition qgsplot.h:769
void setYMinimum(double minimum)
Sets the minimum value of the y axis.
Definition qgsplot.h:748
double xMinimum() const
Returns the minimum value of the x axis.
Definition qgsplot.h:727
void render(QgsRenderContext &context, QgsPlotRenderContext &plotContext, const QgsPlotData &plotData=QgsPlotData()) override
Renders the plot.
Definition qgsplot.cpp:474
void calculateOptimisedIntervals(QgsRenderContext &context, QgsPlotRenderContext &plotContext)
Automatically sets the grid and label intervals to optimal values for display in the given render con...
Definition qgsplot.cpp:1042
QgsPlotAxis & xAxis()
Returns a reference to the plot's x axis.
Definition qgsplot.h:783
double yMinimum() const
Returns the minimum value of the y axis.
Definition qgsplot.h:741
QRectF interiorPlotArea(QgsRenderContext &context, QgsPlotRenderContext &plotContext, const QgsPlotData &plotData=QgsPlotData()) const override
Returns the area of the plot which corresponds to the actual plot content (excluding all titles and o...
Definition qgsplot.cpp:871
void setYMaximum(double maximum)
Sets the maximum value of the y axis.
Definition qgsplot.h:776
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const override
Writes the plot's properties into an XML element.
Definition qgsplot.cpp:422
double xMaximum() const
Returns the maximum value of the x axis.
Definition qgsplot.h:755
virtual double length() const
Returns the planar, 2-dimensional length of the geometry.
Interface for classes which can generate elevation profiles.
static QgsProfileSourceRegistry * profileSourceRegistry()
Returns registry of available profile source implementations.
Represents a coordinate reference system (CRS).
Abstract base class for curved geometry type.
Definition qgscurve.h:36
QgsRange which stores a range of double values.
Definition qgsrange.h:217
QgsDoubleRange visibleElevationRange() const
Returns the elevation range currently visible in the plot.
QgsCurve * profileCurve() const
Returns the profile curve.
void setTolerance(double tolerance)
Sets the profile tolerance (in crs() units).
void setLockAxisScales(bool lock)
Sets whether the distance and elevation scales are locked to each other.
void setProfileCurve(QgsCurve *curve)
Sets the profile curve.
void zoomToRect(const QRectF &rect) override
Zooms the plot to the specified rect in canvas units.
QList< std::variant< QgsMapLayer *, QgsAbstractProfileSource * > > rawSources() const
Returns the list of raw sources included in the profile.
void activeJobCountChanged(int count)
Emitted when the number of active background jobs changes.
QgsElevationProfileCanvas(QWidget *parent=nullptr)
Constructor for QgsElevationProfileCanvas, with the specified parent widget.
void scalePlot(double factor) override
Scales the plot by a specified scale factor.
void paintEvent(QPaintEvent *event) override
QgsDoubleRange visibleDistanceRange() const
Returns the distance range currently visible in the plot.
void cancelJobs() override
Cancel any rendering job, in a blocking way.
QgsCoordinateReferenceSystem crs() const override
Returns the coordinate reference system (CRS) for map coordinates used by the canvas.
void clear()
Clears the current profile.
void setDistanceUnit(Qgis::DistanceUnit unit)
Sets the distance unit used by the canvas.
QgsProfilePoint canvasPointToPlotPoint(QPointF point) const
Converts a canvas point to the equivalent plot point.
void setBackgroundColor(const QColor &color)
Sets the background color to use for the profile canvas.
void render(QgsRenderContext &context, double width, double height, const Qgs2DXyPlot &plotSettings)
Renders a portion of the profile using the specified render context.
QgsPointXY plotPointToCanvasPoint(const QgsProfilePoint &point) const
Converts a plot point to the equivalent canvas point.
QgsPoint toMapCoordinates(const QgsPointXY &point) const override
Converts a point on the canvas to the associated map coordinate.
bool lockAxisScales() const
Returns true if the distance and elevation scales are locked to each other.
void setAxisScaleRatio(double scale)
Sets the ratio of horizontal (distance) to vertical (elevation) scale for the plot.
void setVisiblePlotRange(double minimumDistance, double maximumDistance, double minimumElevation, double maximumElevation)
Sets the visible area of the plot.
void canvasPointHovered(const QgsPointXY &point, const QgsProfilePoint &profilePoint)
Emitted when the mouse hovers over the specified point (in canvas coordinates).
const Qgs2DXyPlot & plot() const
Returns a reference to the 2D plot used by the widget.
void setSubsectionsSymbol(QgsLineSymbol *symbol)
Sets the symbol used to draw the subsections.
void setSources(const QList< std::variant< QgsMapLayer *, QgsAbstractProfileSource * > > &sources)
Sets the list of sources to include in the profile.
QgsPointXY snapToPlot(QPoint point) override
Snap a canvas point to the plot.
void setProject(QgsProject *project)
Sets the project associated with the profile.
QList< QgsMapLayer * > layers() const
Returns the list of layers included in the profile.
void resizeEvent(QResizeEvent *event) override
void centerPlotOn(double x, double y) override
Centers the plot on the plot point corresponding to x, y in canvas units.
void wheelZoom(QWheelEvent *event) override
Zoom plot from a mouse wheel event.
void refresh() override
Triggers a complete regeneration of the profile, causing the profile extraction to perform in the bac...
Qgis::DistanceUnit distanceUnit() const
Returns the distance unit used by the canvas.
double tolerance() const
Returns the tolerance of the profile (in crs() units).
void mouseMoveEvent(QMouseEvent *e) override
void panContentsBy(double dx, double dy) override
Pans the plot contents by dx, dy in canvas units.
void invalidateCurrentPlotExtent()
Invalidates the current plot extent, which means that the visible plot area will be recalculated and ...
QgsPointXY toCanvasCoordinates(const QgsPoint &point) const override
Converts a point in map coordinates to the associated canvas point.
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the crs associated with the canvas' map coordinates.
QList< QgsAbstractProfileSource * > sources() const
Returns the list of sources included in the profile.
double axisScaleRatio() const
Returns the current ratio of horizontal (distance) to vertical (elevation) scale for the plot.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the list of layers to include in the profile.
void zoomFull()
Zooms to the full extent of the profile.
void scaleChanged()
Emitted when the plot scale is changed.
QgsDoubleRange dataElevationRange() const
Returns elevation range of the computed profile results.
void setSnappingEnabled(bool enabled)
Sets whether snapping of cursor points is enabled.
QVector< QgsProfileIdentifyResults > identify(QPointF point)
Identify results visible at the specified plot point.
QRectF plotArea() const
Returns the interior rectangle representing the surface of the plot, in canvas coordinates.
static std::unique_ptr< QgsExpressionContextScope > globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context.
static std::unique_ptr< QgsExpressionContextScope > projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
Does vector analysis using the GEOS library and handles import, export, and exception handling.
Definition qgsgeos.h:192
A line symbol type, for rendering LineString and MultiLineString geometries.
void profileGenerationPropertyChanged()
Emitted when any of the elevation properties which relate solely to generation of elevation profiles ...
void profileRenderingPropertyChanged()
Emitted when any of the elevation properties which relate solely to presentation of elevation results...
Base class for all map layer types.
Definition qgsmaplayer.h:84
virtual QgsAbstractProfileSource * profileSource()
Returns the layer's profile source if it has profile capabilities.
QString id
Definition qgsmaplayer.h:87
Qgis::LayerType type
Definition qgsmaplayer.h:94
void dataChanged()
Data of layer changed.
virtual QgsMapLayerElevationProperties * elevationProperties()
Returns the layer's elevation properties.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
void setLabelSuffixPlacement(Qgis::PlotAxisSuffixPlacement placement)
Sets the placement for the axis label suffixes.
Definition qgsplot.cpp:210
void setLabelSuffix(const QString &suffix)
Sets the axis label suffix.
Definition qgsplot.cpp:200
An abstract class for items that can be placed on a QgsPlotCanvas.
virtual void paint(QPainter *painter)=0
Paints the item.
bool event(QEvent *e) override
QgsPlotCanvas(QWidget *parent=nullptr)
Constructor for QgsPlotCanvas, with the specified parent widget.
void plotAreaChanged()
Emitted whenever the visible area of the plot is changed.
void mouseMoveEvent(QMouseEvent *e) override
void resizeEvent(QResizeEvent *e) override
Contains information about the context of a plot rendering operation.
Definition qgsplot.h:191
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
bool isEmpty() const
Returns true if the geometry is empty.
Definition qgspointxy.h:245
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
double z
Definition qgspoint.h:58
Encapsulates the context in which an elevation profile is to be generated.
double maximumErrorMapUnits() const
Returns the maximum allowed error in the generated result, in profile curve map units.
void setDpi(double dpi)
Sets the dpi (dots per inch) for the profie, to be used in size conversions.
void setMaximumErrorMapUnits(double error)
Sets the maximum allowed error in the generated result, in profile curve map units.
void setDistanceRange(const QgsDoubleRange &range)
Sets the range of distances to include in the generation.
void setElevationRange(const QgsDoubleRange &range)
Sets the range of elevations to include in the generation.
void setMapUnitsPerDistancePixel(double units)
Sets the number of map units per pixel in the distance dimension.
Encapsulates the context of identifying profile results.
double maximumPointElevationDelta
Maximum allowed snapping delta for the elevation values when identifying a point.
double maximumPointDistanceDelta
Maximum allowed snapping delta for the distance values when identifying a point.
QgsProject * project
Associated project.
double displayRatioElevationVsDistance
Display ratio of elevation vs distance units.
double maximumSurfaceDistanceDelta
Maximum allowed snapping delta for the distance values when identifying a continuous elevation surfac...
double maximumSurfaceElevationDelta
Maximum allowed snapping delta for the elevation values when identifying a continuous elevation surfa...
Generates and renders elevation profile plots.
void generationFinished()
Emitted when the profile generation is finished (or canceled).
Encapsulates a point on a distance-elevation profile.
double elevation() const
Returns the elevation of the point.
double distance() const
Returns the distance of the point.
bool isEmpty() const
Returns true if the point is empty.
Encapsulates properties and constraints relating to fetching elevation profiles from different source...
QgsProfileRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate expressions.
QgsProfileRequest & setTransformContext(const QgsCoordinateTransformContext &context)
Sets the transform context, for use when transforming coordinates from a source to the request's crs(...
QgsProfileRequest & setTerrainProvider(QgsAbstractTerrainProvider *provider)
Sets the terrain provider.
QgsProfileRequest & setTolerance(double tolerance)
Sets the tolerance of the request (in crs() units).
QgsProfileRequest & setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the desired Coordinate Reference System (crs) for the profile.
Encapsulates the context of snapping a profile point.
double maximumPointDistanceDelta
Maximum allowed snapping delta for the distance values when snapping to a point.
double maximumSurfaceElevationDelta
Maximum allowed snapping delta for the elevation values when snapping to a continuous elevation surfa...
double maximumPointElevationDelta
Maximum allowed snapping delta for the elevation values when snapping to a point.
double maximumSurfaceDistanceDelta
Maximum allowed snapping delta for the distance values when snapping to a continuous elevation surfac...
double displayRatioElevationVsDistance
Display ratio of elevation vs distance units.
Encapsulates results of snapping a profile point.
bool isValid() const
Returns true if the result is a valid point.
QgsProfilePoint snappedPoint
Snapped point.
void profileSourceUnregistered(const QString &sourceId)
Signal emitted once a profile source is unregistered.
void profileSourceRegistered(const QString &sourceId, const QString &sourceName)
Signal emitted once a profile source is registered.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:114
T lower() const
Returns the lower bound of the range.
Definition qgsrange.h:79
T upper() const
Returns the upper bound of the range.
Definition qgsrange.h:86
A container for the context for various read/write operations on objects.
Contains information about the context of a rendering operation.
void setScaleFactor(double factor)
Sets the scaling factor for the render to convert painter units to physical sizes.
void setDevicePixelRatio(float ratio)
Sets the device pixel ratio.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
static QgsRenderContext fromQPainter(QPainter *painter)
Creates a default render context given a pixel based QPainter destination.
A utility class for dynamic handling of changes to screen properties.
static const QgsSettingsEntryDouble * settingsZoomFactor
Settings entry zoom factor.
static const QgsSettingsEntryBool * settingsReverseWheelZoom
Settings entry reverse wheel zoom.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
static Q_INVOKABLE double fromUnitToUnitFactor(Qgis::DistanceUnit fromUnit, Qgis::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
static Q_INVOKABLE QString toAbbreviatedString(Qgis::DistanceUnit unit)
Returns a translated abbreviation representing a distance unit.
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant &value)
Emitted whenever an attribute value change is done in the edit buffer.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer.
void featureDeleted(QgsFeatureId fid)
Emitted when a feature has been deleted.
void geometryChanged(QgsFeatureId fid, const QgsGeometry &geometry)
Emitted whenever a geometry change is done in the edit buffer.
Contains geos related utilities and functions.
Definition qgsgeos.h:129
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
#define BUILTIN_UNREACHABLE
Definition qgis.h:8483
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.