42 , mLayerGeometryType( layer->geometryType() )
43 , mRenderer( layer->renderer() )
44 , mFields( layer->fields() )
45 , mCrs( layer->
crs() )
47 mName = layerName.isEmpty() ? layer->
id() : layerName;
49 if ( withFeatureLoop )
51 mSource = qgis::make_unique<QgsVectorLayerFeatureSource>(
layer );
120 QSet<QString> attrNames;
121 if ( !
prepare( ctx, attrNames ) )
122 return QList<QgsLabelFeature *>();
142 std::unique_ptr< QgsSymbol > symbol;
151 if ( !symbols.isEmpty() )
153 symbol.reset( symbols.at( 0 )->clone() );
185 std::unique_ptr< QgsAbstractGeometry > obstacleGeom;
187 obstacleGeom = qgis::make_unique< QgsMultiPolygon >();
213 const auto constSymbols = symbols;
218 if ( bounds.isValid() )
219 bounds = bounds.united( static_cast< QgsMarkerSymbol * >( symbol )->bounds( pt, context, fet ) );
221 bounds =
static_cast< QgsMarkerSymbol *
>( symbol )->bounds( pt, context, fet );
226 QVector< double > bX;
227 bX << bounds.left() << bounds.right() << bounds.right() << bounds.left();
228 QVector< double > bY;
229 bY << bounds.top() << bounds.top() << bounds.bottom() << bounds.bottom();
230 std::unique_ptr< QgsLineString > boundLineString = qgis::make_unique< QgsLineString >( bX, bY );
234 for (
int i = 0; i < boundLineString->numPoints(); ++i )
237 static_cast<int>( boundLineString->yAt( i ) ) );
238 boundLineString->setXAt( i, point.
x() );
239 boundLineString->setYAt( i, point.
y() );
252 boundLineString->close();
257 boundLineString->filterVertices( [](
const QgsPoint & point )->
bool 259 return std::isfinite( point.
x() ) && std::isfinite( point.
y() );
261 if ( !boundLineString->isRing() )
265 std::unique_ptr< QgsPolygon > obstaclePolygon = qgis::make_unique< QgsPolygon >();
266 obstaclePolygon->setExteriorRing( boundLineString.release() );
270 static_cast<QgsMultiPolygon *
>( obstacleGeom.get() )->addGeometry( obstaclePolygon.release() );
274 obstacleGeom = std::move( obstaclePolygon );
289 drawCallout( context, label );
307 QRectF rect( outPt.x(), outPt.y(), outPt2.
x() - outPt.x(), outPt2.
y() - outPt.y() );
330 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues = lf->
dataDefinedValues();
335 QgsDebugMsgLevel( QStringLiteral(
"PAL font definedFont: %1, Style: %2" ).arg( dFont.toString(), dFont.styleName() ), 4 );
342 format.
setSize( dFont.pixelSize() );
351 case LabelPosition::QuadrantAboveLeft:
352 case LabelPosition::QuadrantLeft:
353 case LabelPosition::QuadrantBelowLeft:
356 case LabelPosition::QuadrantAbove:
357 case LabelPosition::QuadrantOver:
358 case LabelPosition::QuadrantBelow:
361 case LabelPosition::QuadrantAboveRight:
362 case LabelPosition::QuadrantRight:
363 case LabelPosition::QuadrantBelowRight:
370 QgsPalLabeling::dataDefinedTextStyle( tmpLyr, ddValues );
373 QgsPalLabeling::dataDefinedTextBuffer( tmpLyr, ddValues );
376 QgsPalLabeling::dataDefinedTextFormatting( tmpLyr, ddValues );
379 QgsPalLabeling::dataDefinedShapeBackground( tmpLyr, ddValues );
382 QgsPalLabeling::dataDefinedDropShadow( tmpLyr, ddValues );
390 drawCallout( context, label );
451 QPainter *painter = context.
painter();
469 QRectF rect( 0, 0, outPt2.
x() - outPt.x(), outPt2.
y() - outPt.y() );
471 painter->setRenderHint( QPainter::Antialiasing,
false );
472 painter->translate( QPointF( outPt.x(), outPt.y() ) );
473 painter->rotate( -label->
getAlpha() * 180 / M_PI );
477 painter->setBrush( QColor( 255, 0, 0, 100 ) );
478 painter->setPen( QColor( 255, 0, 0, 150 ) );
482 painter->setBrush( QColor( 0, 255, 0, 100 ) );
483 painter->setPen( QColor( 0, 255, 0, 150 ) );
486 painter->drawRect( rect );
495 QgsTextRenderer::Component component;
496 component.dpiRatio = dpiRatio;
497 component.origin = outPt;
498 component.rotation = label->
getAlpha();
505 QPointF centerPt( outPt );
509 double xc = outPt2.
x() - outPt.x();
510 double yc = outPt2.
y() - outPt.y();
512 double angle = -component.rotation;
513 double xd = xc * std::cos( angle ) - yc * std::sin( angle );
514 double yd = xc * std::sin( angle ) + yc * std::cos( angle );
516 centerPt.setX( centerPt.x() + xd );
517 centerPt.setY( centerPt.y() + yd );
519 component.center = centerPt;
525 component.size = QSizeF( labelWidthPx, labelHeightPx );
543 bool prependSymb =
false;
569 symb = symb + QStringLiteral(
"\n" );
574 symb = QStringLiteral(
"\n" ) + symb;
596 QgsTextRenderer::Component component;
597 component.origin = outPt;
598 component.rotation = label->
getAlpha();
600 QgsTextRenderer::drawTextInternal( drawType, context, tmpLyr.
format(), component, multiLineList, labelfm,
QList< QgsLabelFeature * > mLabels
List of generated.
QColor unplacedLabelColor() const
Returns the color to use when rendering unplaced labels.
static QgsExpressionContextScope * updateSymbolScope(const QgsSymbol *symbol, QgsExpressionContextScope *symbolScope=nullptr)
Updates a symbol scope related to a QgsSymbol to an expression context.
Wrapper for iterator of features from vector data provider or vector layer.
QgsVectorLayerLabelProvider(QgsVectorLayer *layer, const QString &providerId, bool withFeatureLoop, const QgsPalLayerSettings *settings, const QString &layerName=QString())
Convenience constructor to initialize the provider from given vector layer.
QString labelText() const
Text of the label.
A rectangle specified with double values.
QString leftDirectionSymbol
String to use for left direction arrows.
QgsWkbTypes::GeometryType mLayerGeometryType
Geometry type of layer.
void setMapRotation(double degrees, double cx, double cy)
Set map rotation in degrees (clockwise)
QgsTextShadowSettings::ShadowPlacement shadowPlacement() const
Returns the placement for the drop shadow.
QgsPalLayerSettings::Placement mPlacement
Placement strategy.
void registerFeature(const QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **labelFeature=nullptr, QgsGeometry obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling.
QgsFeatureId featureId() const
Returns the unique ID of the feature.
Abstract base class for all rendered symbols.
void render(QgsRenderContext &context, QRectF rect, const double angle, const QgsGeometry &anchor, QgsCalloutContext &calloutContext)
Renders the callout onto the specified render context.
std::unique_ptr< QgsAbstractFeatureSource > mSource
Layer's feature source.
QgsLabelFeature * feature()
Returns the parent feature.
virtual bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
const QgsLabelingEngine * mEngine
Associated labeling engine.
Contains additional contextual information about the context in which a callout is being rendered...
Draw shadow under buffer.
UpsideDownLabels upsidedownLabels
Controls whether upside down labels are displayed and how they are handled.
Place direction symbols on below label.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
double mPriority
Default priority of labels.
QgsTextShadowSettings & shadow()
Returns a reference to the text drop shadow settings.
double getY(int i=0) const
Returns the down-left y coordinate.
A class to represent a 2D point.
HAlignment
Horizontal alignment.
void setFont(const QFont &font)
Sets the font used for rendering text.
void stopRender(QgsRenderContext &context) override
To be called after rendering is complete.
const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > & dataDefinedValues() const
Gets data-defined values.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
Class that adds extra information to QgsLabelFeature for text labels.
GEOSGeometry * geometry() const
Gets access to the associated geometry.
bool addDirectionSymbol
If true, '<' or '>' (or custom strings set via leftDirectionSymbol and rightDirectionSymbol) will be ...
A geometry is the spatial representation of a feature.
Whether to only draw the label rect and not the actual label text (used for unit tests) ...
bool drawLabels
Whether to draw labels for this layer.
bool mergeLines
true if connected line features with identical label text should be merged prior to generating label ...
MultiLineAlign multilineAlign
Horizontal alignment of multi-line labels.
FeaturePart * getFeaturePart()
Returns the feature corresponding to this labelposition.
virtual DrawOrder drawOrder() const
Returns the desired drawing order (stacking) to use while rendering this callout. ...
Label-specific draw mode.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
const QgsCoordinateReferenceSystem & crs
bool hasGeometry() const
Returns true if the feature has an associated geometry.
int autoWrapLength
If non-zero, indicates that label text should be automatically wrapped to (ideally) the specified num...
QgsCoordinateTransform ct
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored)
bool reverseDirectionSymbol
True if direction symbols should be reversed.
A marker symbol type, for rendering Point and MultiPoint geometries.
ShapeType type() const
Returns the type of background shape (e.g., square, ellipse, SVG).
void setFormat(const QgsTextFormat &format)
Sets the label text formatting settings, e.g., font settings, buffer settings, etc.
virtual QgsSymbolList originalSymbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const
Equivalent of originalSymbolsForFeature() call extended to support renderers that may use more symbol...
bool isActive(int key) const override
Returns true if the collection contains an active property with the specified key.
Whether adjacent lines (with the same label text) should be merged.
The QgsMapSettings class contains configuration for rendering of the map.
QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &context) override
Returns list of label features (they are owned by the provider and thus deleted on its destruction) ...
QgsMapLayer * layer() const
Returns the associated layer, or nullptr if no layer is associated with the provider.
void transformInPlace(double &x, double &y) const
Transform device coordinates to map coordinates.
void init()
initialization method - called from constructors
Perform transforms between map coordinates and device coordinates.
QgsPointXY transform(const QgsPointXY &p) const
Transform the point from map (world) coordinates to device coordinates.
QgsExpressionContextScope * lastScope()
Returns the last scope added to the context.
ObstacleType obstacleType
Controls how features act as obstacles for labels.
QList< QgsSymbol * > QgsSymbolList
bool displayAll
If true, all features will be labelled even when overlaps occur.
void setSize(double size)
Sets the size for rendered text.
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
const QgsLabelingEngineSettings & engineSettings() const
Gets associated labeling engine settings.
static std::unique_ptr< QgsAbstractGeometry > fromGeos(const GEOSGeometry *geos)
Create a geometry from a GEOSGeometry.
Utility class for identifying a unique vertex within a geometry.
#define QgsDebugMsgLevel(str, level)
Render callouts below their individual associated labels, some callouts may be drawn over other label...
const QgsRectangle & extent() const
When rendering a map layer, calling this method returns the "clipping" extent for the layer (in the l...
QgsPalLayerSettings mSettings
Layer's labeling configuration.
const QgsPalLayerSettings & settings() const
Returns the layer's settings.
LabelPosition * getNextPart() const
void setColor(const QColor &color)
Sets the color that text will be rendered in.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
Flags mFlags
Flags altering drawing and registration of features.
Whether location of centroid must be inside of polygons.
bool allFeaturePartsLabeled
true if all parts of associated feature were labeled
Quadrant getQuadrant() const
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
QgsTextBackgroundSettings & background()
Returns a reference to the text background settings.
QgsTextBufferSettings & buffer()
Returns a reference to the text buffer settings.
void setSizeUnit(QgsUnitTypes::RenderUnit unit)
Sets the units for the size of rendered text.
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
QString text(int partId) const
Returns the text component corresponding to a specified label part.
Whether all features will be labelled even though overlaps occur.
Single scope for storing variables and functions for use within a QgsExpressionContext.
Render callouts below all labels.
Point geometry type, with support for z-dimension and m-values.
The QgsAbstractLabelProvider class is an interface class.
const QgsTextFormat & format() const
Returns the label text formatting settings, e.g., font settings, buffer settings, etc...
Place direction symbols on above label.
Draw shadow below all text components.
virtual void registerFeature(const QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling as one or more QgsLabelFeature objects stored into mLabels...
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsExpressionContext & expressionContext()
Gets the expression context.
QString wrapChar
Wrapping character string.
bool valueAsBool(int key, const QgsExpressionContext &context, bool defaultValue=false, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as an boolean...
TextPart
Components of text.
QgsFields mFields
Layer's fields.
QString rightDirectionSymbol
String to use for right direction arrows.
Arranges candidates parallel to a generalised line representing the feature or parallel to a polygon'...
Contains information about the context of a rendering operation.
double convertToPainterUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to painter units (pixels).
QFont definedFont()
Font to be used for rendering.
bool enabled() const
Returns true if the the callout is enabled.
bool hasFixedPosition() const
Whether the label should use a fixed position instead of being automatically placed.
QPainter * painter()
Returns the destination QPainter for the render operation.
The QgsLabelFeature class describes a feature that should be used within the labeling engine...
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
double getAlpha() const
Returns the angle to rotate text (in rad).
Multi polygon geometry collection.
QString mName
Name of the layer.
bool enabled() const
Returns whether the shadow is enabled.
Struct for storing maximum and minimum scales for measurements in map units.
QgsCoordinateReferenceSystem mCrs
Layer's CRS.
bool conflictsWithObstacle() const
Returns whether the position is marked as conflicting with an obstacle feature.
double getX(int i=0) const
Returns the down-left x coordinate.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
~QgsVectorLayerLabelProvider() override
const QgsMapSettings & mapSettings() const
Gets associated map settings.
bool enabled() const
Returns whether the background is enabled.
bool testFlag(Flag f) const
Test whether a particular flag is enabled.
QgsLabelingResults * results() const
For internal use by the providers.
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
QString mProviderId
Associated provider ID (one layer may have multiple providers, e.g. in rule-based labeling) ...
LabelPosition is a candidate feature label position.
QgsPalLayerSettings::ObstacleType mObstacleType
Type of the obstacle of feature geometries.
virtual void startRender(QgsRenderContext &context)
To be called before rendering of labels begins.
bool enabled() const
Returns whether the buffer is enabled.
QgsPalLayerSettings::UpsideDownLabels mUpsidedownLabels
How to handle labels that would be upside down.
void setShadowPlacement(QgsTextShadowSettings::ShadowPlacement placement)
Sets the placement for the drop shadow.
Draw shadow under background shape.
void startRender(QgsRenderContext &context)
Prepares the label settings for rendering.
QgsCallout * callout() const
Returns the label callout renderer, responsible for drawing label callouts.
Whether the labels should be rendered.
QgsWkbTypes::GeometryType type
Custom exception class for Coordinate Reference System related exceptions.
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
bool nextFeature(QgsFeature &f)
void drawLabelBackground(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw the background for the specified label.
void startRender(QgsRenderContext &context) override
To be called before rendering of labels begins.
Container for all settings relating to text rendering.
QFontMetricsF * labelFontMetrics()
Metrics of the font for rendering.
bool centroidInside
true if centroid positioned labels must be placed inside their corresponding feature polygon...
virtual void stopRender(QgsRenderContext &context)
To be called after rendering is complete.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
virtual int nCoordinates() const
Returns the number of nodes contained in the geometry.
Represents a vector layer which manages a vector based data sets.
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
QString mLayerId
Associated layer's ID, if applicable.
bool labelAllParts() const
Returns true if all parts of the feature should be labeled.
QFont font() const
Returns the font used for rendering text.
bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames, const QgsFields &fields, const QgsMapSettings &mapSettings, const QgsCoordinateReferenceSystem &crs)
Prepare for registration of features.
int priority
Label priority.
QgsFeatureRenderer * mRenderer
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
void drawLabel(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw this label at the position determined by the labeling engine.
void drawLabelPrivate(pal::LabelPosition *label, QgsRenderContext &context, QgsPalLayerSettings &tmpLyr, QgsTextRenderer::TextPart drawType, double dpiRatio=1.0) const
Internal label drawing method.
bool useMaxLineLengthForAutoWrap
If true, indicates that when auto wrapping label text the autoWrapLength length indicates the maximum...
static QStringList splitToLines(const QString &text, const QString &wrapCharacter, int autoWrapLength=0, bool useMaxLineLengthWhenAutoWrapping=true)
Splits a text string to a list of separate lines, using a specified wrap character (wrapCharacter)...
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label's property collection, used for data defined overrides.
static QgsGeometry getPointObstacleGeometry(QgsFeature &fet, QgsRenderContext &context, const QgsSymbolList &symbols)
Returns the geometry for a point feature which should be used as an obstacle for labels.
void stopRender(QgsRenderContext &context)
Finalises the label settings after use.
DirectionSymbols placeDirectionSymbol
Placement option for direction symbols.
void drawUnplacedLabel(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw an unplaced label.