QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgsrubberband_impl.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsrubberband_impl.cpp
3 --------------------------------------
4 Date : July 2026
5 Copyright : (C) 2026 by Nyall Dawson
6 Email : nyall.dawson@gmail.com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsrubberband_impl.h"
17
19#include "qgslabelingresults.h"
20#include "qgsmapcanvas.h"
21#include "qgspainting.h"
22#include "qgstextrenderer.h"
23#include "qgsvectorlayer.h"
24
27 , mLayer( layer )
28{
29 QgsFeature f;
30 QgsFeatureIterator it = mLayer->getFeatures( qgis::listToSet( fids ) );
31 mFeatures.resize( fids.size() );
32 int index = 0;
33 while ( it.nextFeature( f ) )
34 {
35 mFeatures[index] = f;
36 index++;
37 }
38}
39
41{
43 if ( !rubberBand || !mLayer || !mLayer->labelsEnabled() || !mLayer->labeling() || mFeatures.empty() )
44 return;
45
46 QgsMapCanvas *canvas = rubberBand->canvas();
47 if ( !canvas )
48 return;
49
50 // fetch current rubber band geometry
51 QgsGeometry previewGeom = rubberBand->asGeometry();
52 if ( previewGeom.isEmpty() )
53 return;
54
56
57 const double previousReferenceScale = context.symbologyReferenceScale();
58 if ( const QgsFeatureRenderer *renderer = mLayer->renderer() )
59 {
60 context.setSymbologyReferenceScale( renderer->referenceScale() );
61 }
62
63 QgsExpressionContextScopePopper layerScopePopper( context.expressionContext(), mLayer->createExpressionContextScope() );
64
66
67 QgsExpressionContextScopePopper scopePopper( context.expressionContext(), featureScope );
69
70 // set up a super minimal, fast labeling engine. Why? Well...
71 // we can't just use QgsTextRenderer here, as that won't fully reflect the actual appearance
72 // of the labels actually rendered for the features. Eg it won't respect settings like text repeat distances,
73 // anchor points, overrun, curved placement modes, etc.
74 // So to get a useful preview we need to use the actual labeling engine to render the label.
75 // But we also don't need a lot of the weight of pal labeling, eg we only need to render the
76 // single least-cost candidate for each feature, we won't consider obstacles or overlaps, we don't
77 // need the label search tree, etc.
78 // Disabling all this gives us a very lean label engine, which is quite cheap to use and gives
79 // perfect 1:1 previews of the actual label to be rendered.
80 QgsMapSettings mapSettings = canvas->mapSettings();
82 QgsLabelingEngineSettings labelSettings = mapSettings.labelingEngineSettings();
85 labelSettings.setFlag( Qgis::LabelingFlag::IgnoreObstacles, true );
87 labelSettings.setFlag( Qgis::LabelingFlag::IgnoreOverlaps, true );
88 mapSettings.setLabelingEngineSettings( labelSettings );
89 QgsDefaultLabelingEngine engine( mapSettings );
90
91 QgsPalLayerSettings settings = mLayer->labeling()->settings();
92 auto provider = new QgsVectorLayerLabelProvider( mLayer, QString(), false, &settings );
93 engine.addProvider( provider );
94
95 QSet<QString> attributeNames;
96 if ( !provider->prepare( context, attributeNames ) )
97 {
98 context.setSymbologyReferenceScale( previousReferenceScale );
99 return;
100 }
101
102 if ( mFeatures.size() > 1 )
103 {
104 // when multiple features are being rendered, each individual part of the rubber
105 // band's geometry corresponds to an individual feature,
106 // so we re-associate them here
107 // NOTE: we need a better way to handle this, it assumes all features are single-parts themselves...
108 const QVector< QgsGeometry> previewGeomParts = previewGeom.asGeometryCollection();
109 int index = 0;
110 for ( const QgsFeature &feature : std::as_const( mFeatures ) )
111 {
112 if ( index >= previewGeomParts.size() )
113 break;
114
115 QgsFeature tempFeature = feature;
116 tempFeature.setGeometry( previewGeomParts.at( index ) );
117
118 featureScope->setFeature( tempFeature );
119 featureScope->setFields( tempFeature.fields() );
120 provider->registerFeature( tempFeature, context, QgsLabelFeatureDetails() );
121 index++;
122 }
123 }
124 else if ( mFeatures.size() == 1 )
125 {
126 QgsFeature tempFeature = mFeatures.at( 0 );
127 tempFeature.setGeometry( previewGeom );
128 featureScope->setFeature( tempFeature );
129 featureScope->setFields( tempFeature.fields() );
130 provider->registerFeature( tempFeature, context, QgsLabelFeatureDetails() );
131 }
132
133 QgsScopedQPainterState painterState( context.painter() );
134 context.painter()->translate( -rubberBand->pos() );
135
136 // running the engine calculates the placement and does the actual rendering:
137 engine.run( context );
138
139 if ( QgsLabelingResults *results = engine.results() )
140 {
141 mBoundingRect = QRectF();
142 const QList<QgsLabelPosition> labelPosList = results->allLabels();
143 const QgsMapToPixel *m2p = canvas->getCoordinateTransform();
144 const QPointF itemPos = rubberBand->pos();
145
146 for ( const QgsLabelPosition &labelPos : labelPosList )
147 {
148 for ( int i = 0; i < 4; ++i )
149 {
150 // map point -> canvas pixel -> local item coordinates
151 const QPointF canvasPt = m2p->transform( labelPos.cornerPoints[i] ).toQPointF();
152 const QPointF localPt = canvasPt - itemPos;
153 if ( mBoundingRect.isEmpty() )
154 mBoundingRect = QRectF( localPt, QSizeF( 1, 1 ) );
155 else
156 mBoundingRect = mBoundingRect.united( QRectF( localPt, QSizeF( 1, 1 ) ) );
157 }
158 }
159 }
160
161 context.setSymbologyReferenceScale( previousReferenceScale );
162}
163
165{
166 return mBoundingRect;
167}
@ DisableSearchTree
Disable the creation of the label search tree.
Definition qgis.h:3087
@ IgnoreObstacles
Disable obstacle handling.
Definition qgis.h:3084
@ SingleCandidateOnly
Generate only the single least-cost candidate for each feature. Useful for fast labeling,...
Definition qgis.h:3085
@ IgnoreOverlaps
Disable overlap detection and search solver, immediately returning lowest cost candidate per feature.
Definition qgis.h:3086
@ UsePartialCandidates
Whether to use also label candidates that are partially outside of the map view.
Definition qgis.h:3076
@ RecordProfile
Enable run-time profiling while rendering.
Definition qgis.h:2996
@ Reverse
Reverse/inverse transform (from destination to source).
Definition qgis.h:2884
@ RecordProfile
Enable run-time profiling while rendering.
Definition qgis.h:2960
Default QgsLabelingEngine implementation, which completes the whole labeling operation (including lab...
void run(QgsRenderContext &context) override
Runs the labeling job.
RAII class to pop scope from an expression context on destruction.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the scope.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the scope.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Abstract base class for all 2D vector feature renderers.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsFields fields
Definition qgsfeature.h:65
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
A geometry is the spatial representation of a feature.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
QVector< QgsGeometry > asGeometryCollection() const
Returns the contents of the geometry as a list of single-part geometries.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
Encapsulates details for an individual feature to label.
Represents the calculated placement of a map label.
Stores global configuration for labeling engine.
void setFlag(Qgis::LabelingFlag f, bool enabled=true)
Sets whether a particual flag is enabled.
QString addProvider(QgsAbstractLabelProvider *provider)
Adds a provider of label features.
QgsLabelingResults * results() const
For internal use by the providers.
Stores computed placement from labeling engine.
Map canvas is a class for displaying all GIS data types on a canvas.
const QgsMapToPixel * getCoordinateTransform()
Gets the current coordinate transform.
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
Contains configuration for rendering maps.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
QgsCoordinateTransform layerTransform(const QgsMapLayer *layer) const
Returns the coordinate transform from layer's CRS to destination CRS.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets the global configuration of the labeling engine.
void setFlag(Qgis::MapSettingsFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
Perform transforms between map coordinates and device coordinates.
QgsPointXY transform(const QgsPointXY &p) const
Transforms a point p from map (world) coordinates to device coordinates.
Contains settings for how a map layer will be labeled.
QPointF toQPointF() const
Converts a point to a QPointF.
Definition qgspointxy.h:168
Contains information about the context of a rendering operation.
double symbologyReferenceScale() const
Returns the symbology reference scale.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setFlag(Qgis::RenderContextFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
void setSymbologyReferenceScale(double scale)
Sets the symbology reference scale.
QgsRubberBandPreviewItem(QgsRubberBand *rubberBand)
Constructor for a QgsRubberBandPreviewItem, attached to the specified rubberBand.
QgsRubberBand * rubberBand()
Returns the rubber band associated with the item.
Responsible for drawing transient features (e.g.
Scoped object for saving and restoring a QPainter object's state.
Implements a label provider for vector layers.
QRectF boundingRect() const override
Returns the bounding rect required for drawing the preview item.
void render(QgsRenderContext &context) final
Renders the custom preview overlay using the specified render context.
QgsVectorLayerLabelRubberBandPreview(QgsRubberBand *rubberBand, const QList< QgsFeatureId > &fids, QgsVectorLayer *layer)
Constructor for QgsVectorLayerLabelRubberBandPreview.
Represents a vector layer which manages a vector based dataset.