44 #include <QTextDocument>
45 #include <QTextFragment>
52 , mLayerGeometryType( layer->geometryType() )
53 , mRenderer( layer->renderer() )
54 , mFields( layer->fields() )
55 , mCrs( layer->
crs() )
59 if ( withFeatureLoop )
61 mSource = std::make_unique<QgsVectorLayerFeatureSource>(
layer );
70 , mLayerGeometryType( geometryType )
71 , mRenderer( nullptr )
143 QSet<QString> attrNames;
144 if ( !
prepare( ctx, attrNames ) )
145 return QList<QgsLabelFeature *>();
174 if ( !symbols.isEmpty() )
176 symbol = symbols.at( 0 );
208 std::unique_ptr< QgsAbstractGeometry > obstacleGeom;
210 obstacleGeom = std::make_unique< QgsMultiPolygon >();
213 for (
int i = 0; i < fet.
geometry().constGet()->nCoordinates(); ++i )
236 const auto constSymbols = symbols;
241 if ( bounds.isValid() )
242 bounds = bounds.united(
static_cast< QgsMarkerSymbol *
>( symbol )->bounds( pt, context, fet ) );
244 bounds =
static_cast< QgsMarkerSymbol *
>( symbol )->bounds( pt, context, fet );
249 QVector< double > bX;
250 bX << bounds.left() << bounds.right() << bounds.right() << bounds.left();
251 QVector< double > bY;
252 bY << bounds.top() << bounds.top() << bounds.bottom() << bounds.bottom();
253 std::unique_ptr< QgsLineString > boundLineString = std::make_unique< QgsLineString >( bX, bY );
257 for (
int i = 0; i < boundLineString->numPoints(); ++i )
260 static_cast<int>( boundLineString->yAt( i ) ) );
261 boundLineString->setXAt( i, point.
x() );
262 boundLineString->setYAt( i, point.
y() );
275 boundLineString->close();
280 boundLineString->filterVertices( [](
const QgsPoint & point )->
bool
282 return std::isfinite( point.
x() ) && std::isfinite( point.
y() );
284 if ( !boundLineString->isRing() )
288 std::unique_ptr< QgsPolygon > obstaclePolygon = std::make_unique< QgsPolygon >();
289 obstaclePolygon->setExteriorRing( boundLineString.release() );
293 static_cast<QgsMultiPolygon *
>( obstacleGeom.get() )->addGeometry( obstaclePolygon.release() );
297 obstacleGeom = std::move( obstaclePolygon );
312 drawCallout( context, label );
330 QRectF rect( outPt.x(), outPt.y(), outPt2.
x() - outPt.x(), outPt2.
y() - outPt.y() );
339 const QList< QgsCalloutPosition > renderedPositions = calloutContext.
positions();
364 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues = lf->
dataDefinedValues();
369 QgsDebugMsgLevel( QStringLiteral(
"PAL font definedFont: %1, Style: %2" ).arg( dFont.toString(), dFont.styleName() ), 4 );
376 format.
setSize( dFont.pixelSize() );
385 case LabelPosition::QuadrantAboveLeft:
386 case LabelPosition::QuadrantLeft:
387 case LabelPosition::QuadrantBelowLeft:
390 case LabelPosition::QuadrantAbove:
391 case LabelPosition::QuadrantOver:
392 case LabelPosition::QuadrantBelow:
395 case LabelPosition::QuadrantAboveRight:
396 case LabelPosition::QuadrantRight:
397 case LabelPosition::QuadrantBelowRight:
404 QgsPalLabeling::dataDefinedTextStyle( tmpLyr, ddValues );
407 QgsPalLabeling::dataDefinedTextBuffer( tmpLyr, ddValues );
410 QgsPalLabeling::dataDefinedTextMask( tmpLyr, ddValues );
413 QgsPalLabeling::dataDefinedTextFormatting( tmpLyr, ddValues );
416 QgsPalLabeling::dataDefinedShapeBackground( tmpLyr, ddValues );
419 QgsPalLabeling::dataDefinedDropShadow( tmpLyr, ddValues );
427 drawCallout( context, label );
491 QPainter *painter = context.
painter();
509 QRectF rect( 0, 0, outPt2.
x() - outPt.x(), outPt2.
y() - outPt.y() );
511 painter->setRenderHint( QPainter::Antialiasing,
false );
512 painter->translate( QPointF( outPt.x(), outPt.y() ) );
513 painter->rotate( -label->
getAlpha() * 180 / M_PI );
517 painter->setBrush( QColor( 255, 0, 0, 100 ) );
518 painter->setPen( QColor( 255, 0, 0, 150 ) );
522 painter->setBrush( QColor( 0, 255, 0, 100 ) );
523 painter->setPen( QColor( 0, 255, 0, 150 ) );
526 painter->drawRect( rect );
535 QgsTextRenderer::Component component;
536 component.dpiRatio = dpiRatio;
537 component.origin = outPt;
538 component.rotation = label->
getAlpha();
543 QPointF centerPt( outPt );
547 double xc = outPt2.
x() - outPt.x();
548 double yc = outPt2.
y() - outPt.y();
550 double angle = -component.rotation;
551 double xd = xc * std::cos(
angle ) - yc * std::sin(
angle );
552 double yd = xc * std::sin(
angle ) + yc * std::cos(
angle );
554 centerPt.setX( centerPt.x() + xd );
555 centerPt.setY( centerPt.y() + yd );
557 component.center = centerPt;
563 component.size = QSizeF( labelWidthPx, labelHeightPx );
588 bool prependSymb =
false;
615 symb = symb + QStringLiteral(
"\n" );
620 symb = QStringLiteral(
"\n" ) + symb;
645 QgsTextRenderer::Component component;
646 component.origin = outPt;
647 component.rotation = label->
getAlpha();
654 for (
const QString &line : multiLineList )
662 QgsTextRenderer::drawTextInternal( drawType, context, tmpLyr.
format(), component, document, labelfm,
@ NeverShow
Never show unplaced labels, regardless of the engine setting.
virtual int nCoordinates() const
Returns the number of nodes contained in the geometry.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
The QgsAbstractLabelProvider class is an interface class.
QgsLabelObstacleSettings::ObstacleType mObstacleType
Type of the obstacle of feature geometries.
QString mName
Name of the layer.
virtual void stopRender(QgsRenderContext &context)
To be called after rendering is complete.
QgsMapLayer * layer() const
Returns the associated layer, or nullptr if no layer is associated with the provider.
QString mLayerId
Associated layer's ID, if applicable.
QgsPalLayerSettings::UpsideDownLabels mUpsidedownLabels
How to handle labels that would be upside down.
double mPriority
Default priority of labels.
const QgsLabelingEngine * mEngine
Associated labeling engine.
Flags mFlags
Flags altering drawing and registration of features.
virtual void startRender(QgsRenderContext &context)
To be called before rendering of labels begins.
@ DrawAllLabels
Whether all features will be labelled even though overlaps occur.
@ MergeConnectedLines
Whether adjacent lines (with the same label text) should be merged.
@ DrawLabels
Whether the labels should be rendered.
@ CentroidMustBeInside
Whether location of centroid must be inside of polygons.
QString layerId() const
Returns ID of associated layer, or empty string if no layer is associated with the provider.
QString providerId() const
Returns provider ID - useful in case there is more than one label provider within a layer (e....
QgsPalLayerSettings::Placement mPlacement
Placement strategy.
QString mProviderId
Associated provider ID (one layer may have multiple providers, e.g. in rule-based labeling)
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.
Represents the calculated placement of a map label callout line.
Contains additional contextual information about the context in which a callout is being rendered.
bool allFeaturePartsLabeled
true if all parts of associated feature were labeled
QList< QgsCalloutPosition > positions() const
Returns the list of rendered callout positions.
QgsCoordinateReferenceSystem originalFeatureCrs
Contains the CRS of the original feature associated with this callout.
void render(QgsRenderContext &context, const QRectF &rect, const double angle, const QgsGeometry &anchor, QgsCalloutContext &calloutContext)
Renders the callout onto the specified render context.
@ OrderBelowIndividualLabels
Render callouts below their individual associated labels, some callouts may be drawn over other label...
@ OrderBelowAllLabels
Render callouts below all labels.
virtual DrawOrder drawOrder() const
Returns the desired drawing order (stacking) to use while rendering this callout.
bool enabled() const
Returns true if the the callout is enabled.
This class represents a coordinate reference system (CRS).
Custom exception class for Coordinate Reference System related exceptions.
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsExpressionContextScope * updateSymbolScope(const QgsSymbol *symbol, QgsExpressionContextScope *symbolScope=nullptr)
Updates a symbol scope related to a QgsSymbol to an expression context.
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
QgsExpressionContextScope * lastScope()
Returns the last scope added to the context.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
virtual QgsSymbolList originalSymbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const
Equivalent of originalSymbolsForFeature() call extended to support renderers that may use more symbol...
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Container of fields for a vector layer.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsWkbTypes::GeometryType type
static std::unique_ptr< QgsAbstractGeometry > fromGeos(const GEOSGeometry *geos)
Create a geometry from a GEOSGeometry.
The QgsLabelFeature class describes a feature that should be used within the labeling engine.
QgsCoordinateReferenceSystem originalFeatureCrs() const
Returns the original layer CRS of the feature associated with the label.
bool hasFixedPosition() const
Whether the label should use a fixed position instead of being automatically placed.
QString labelText() const
Text of the label.
GEOSGeometry * geometry() const
Gets access to the associated geometry.
bool labelAllParts() const
Returns true if all parts of the feature should be labeled.
bool reverseDirectionSymbol() const
Returns true if direction symbols should be reversed.
DirectionSymbolPlacement directionSymbolPlacement() const
Returns the placement for direction symbols.
QString leftDirectionSymbol() const
Returns the string to use for left direction arrows.
@ SymbolLeftRight
Place direction symbols on left/right of label.
@ SymbolAbove
Place direction symbols on above label.
@ SymbolBelow
Place direction symbols on below label.
QString rightDirectionSymbol() const
Returns the string to use for right direction arrows.
bool addDirectionSymbol() const
Returns true if '<' or '>' (or custom strings set via leftDirectionSymbol and rightDirectionSymbol) w...
bool mergeLines() const
Returns true if connected line features with identical label text should be merged prior to generatin...
ObstacleType type() const
Returns how features act as obstacles for labels.
bool testFlag(Flag f) const
Test whether a particular flag is enabled.
Flags flags() const
Gets flags of the labeling engine.
@ DrawUnplacedLabels
Whether to render unplaced labels as an indicator/warning for users.
@ DrawLabelRectOnly
Whether to only draw the label rect and not the actual label text (used for unit tests)
QColor unplacedLabelColor() const
Returns the color to use when rendering unplaced labels.
const QgsLabelingEngineSettings & engineSettings() const
Gets associated labeling engine settings.
const QgsMapSettings & mapSettings() const
Gets associated map settings.
QgsLabelingResults * results() const
For internal use by the providers.
Base class for all map layer types.
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
The QgsMapSettings class contains configuration for rendering of the map.
Perform transforms between map coordinates and device coordinates.
void setMapRotation(double degrees, double cx, double cy)
Set map rotation in degrees (clockwise)
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
QgsPointXY transform(const QgsPointXY &p) const
Transform the point p from map (world) coordinates to device coordinates.
void transformInPlace(double &x, double &y) const
Transforms device coordinates to map coordinates.
Struct for storing maximum and minimum scales for measurements in map units.
A marker symbol type, for rendering Point and MultiPoint geometries.
Multi polygon geometry collection.
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).
Contains settings for how a map layer will be labeled.
void setFormat(const QgsTextFormat &format)
Sets the label text formatting settings, e.g., font settings, buffer settings, etc.
void startRender(QgsRenderContext &context)
Prepares the label settings for rendering.
bool displayAll
If true, all features will be labelled even when overlaps occur.
QString wrapChar
Wrapping character string.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label's property collection, used for data defined overrides.
QgsCoordinateTransform ct
bool drawLabels
Whether to draw labels for this layer.
QgsCallout * callout() const
Returns the label callout renderer, responsible for drawing label callouts.
void registerFeature(const QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **labelFeature=nullptr, QgsGeometry obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling.
@ Curved
Arranges candidates following the curvature of a line feature. Applies to line layers only.
@ Line
Arranges candidates parallel to a generalised line representing the feature or parallel to a polygon'...
bool centroidInside
true if centroid positioned labels must be placed inside their corresponding feature polygon,...
int priority
Label priority.
MultiLineAlign multilineAlign
Horizontal alignment of multi-line labels.
@ CalloutDraw
Show callout.
const QgsLabelLineSettings & lineSettings() const
Returns the label line settings, which contain settings related to how the label engine places and fo...
const QgsLabelObstacleSettings & obstacleSettings() const
Returns the label obstacle settings.
bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames, const QgsFields &fields, const QgsMapSettings &mapSettings, const QgsCoordinateReferenceSystem &crs)
Prepare for registration of features.
const QgsTextFormat & format() const
Returns the label text formatting settings, e.g., font settings, buffer settings, etc.
UpsideDownLabels upsidedownLabels
Controls whether upside down labels are displayed and how they are handled.
int autoWrapLength
If non-zero, indicates that label text should be automatically wrapped to (ideally) the specified num...
Qgis::UnplacedLabelVisibility unplacedVisibility() const
Returns the layer's unplaced label visibility.
bool useMaxLineLengthForAutoWrap
If true, indicates that when auto wrapping label text the autoWrapLength length indicates the maximum...
void stopRender(QgsRenderContext &context)
Finalises the label settings after use.
A class to represent a 2D point.
QPointF toQPointF() const
Converts a point to a QPointF.
Point geometry type, with support for z-dimension and m-values.
bool isActive(int key) const override
Returns true if the collection contains an active property with the specified key.
A rectangle specified with double values.
Contains information about the context of a rendering operation.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
void setCurrentMaskId(int id)
Stores a mask id as the "current" one.
double convertToPainterUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to painter units (pixels).
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
const QgsRectangle & extent() const
When rendering a map layer, calling this method returns the "clipping" extent for the layer (in the l...
const QgsMaskIdProvider * maskIdProvider() const
Returns the mask id provider attached to the context.
Abstract base class for all rendered symbols.
bool enabled() const
Returns whether the background is enabled.
ShapeType type() const
Returns the type of background shape (e.g., square, ellipse, SVG).
@ ShapeMarkerSymbol
Marker symbol.
Represents a block of text consisting of one or more QgsTextFragment objects.
bool enabled() const
Returns whether the buffer is enabled.
Stores information relating to individual character formatting.
Represents a document consisting of one or more QgsTextBlock objects.
void append(const QgsTextBlock &block)
Appends a block to the document.
Container for all settings relating to text rendering.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
void setSize(double size)
Sets the size for rendered text.
void setFont(const QFont &font)
Sets the font used for rendering text.
QgsTextBackgroundSettings & background()
Returns a reference to the text background settings.
bool allowHtmlFormatting() const
Returns true if text should be treated as a HTML document and HTML tags should be used for formatting...
void setSizeUnit(QgsUnitTypes::RenderUnit unit)
Sets the units for the size of rendered text.
QgsTextShadowSettings & shadow()
Returns a reference to the text drop shadow settings.
QFont font() const
Returns the font used for rendering text.
QgsTextBufferSettings & buffer()
Returns a reference to the text buffer settings.
Stores a fragment of text along with formatting overrides to be used when rendering the fragment.
Class that adds extra information to QgsLabelFeature for text labels.
const QMap< QgsPalLayerSettings::Property, QVariant > & dataDefinedValues() const
Gets data-defined values.
QgsTextDocument document() const
Returns the document for the label.
QFont definedFont()
Font to be used for rendering.
QgsTextCharacterFormat characterFormat(int partId) const
Returns the character format corresponding to the specified label part.
QString text(int partId) const
Returns the text component corresponding to a specified label part.
QFontMetricsF * labelFontMetrics()
Metrics of the font for rendering.
TextPart
Components of text.
@ Buffer
Buffer component.
@ Background
Background shape.
HAlignment
Horizontal alignment.
@ AlignCenter
Center align.
@ AlignJustify
Justify align.
@ Label
Label-specific draw mode.
bool enabled() const
Returns whether the shadow is enabled.
void setShadowPlacement(QgsTextShadowSettings::ShadowPlacement placement)
Sets the placement for the drop shadow.
@ ShadowBuffer
Draw shadow under buffer.
@ ShadowShape
Draw shadow under background shape.
@ ShadowLowest
Draw shadow below all text components.
@ ShadowText
Draw shadow under text.
QgsTextShadowSettings::ShadowPlacement shadowPlacement() const
Returns the placement for the drop shadow.
@ RenderMapUnits
Map units.
void stopRender(QgsRenderContext &context) override
To be called after rendering is complete.
QgsCoordinateReferenceSystem mCrs
Layer's CRS.
void drawLabelPrivate(pal::LabelPosition *label, QgsRenderContext &context, QgsPalLayerSettings &tmpLyr, QgsTextRenderer::TextPart drawType, double dpiRatio=1.0) const
Internal label drawing method.
virtual bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
void drawUnplacedLabel(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw an unplaced label.
QgsFields mFields
Layer's fields.
QList< QgsLabelFeature * > mLabels
List of generated.
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.
void startRender(QgsRenderContext &context) override
To be called before rendering of labels begins.
~QgsVectorLayerLabelProvider() override
const QgsPalLayerSettings & settings() const
Returns the layer's settings.
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.
QgsWkbTypes::GeometryType mLayerGeometryType
Geometry type of layer.
QgsPalLayerSettings mSettings
Layer's labeling configuration.
std::unique_ptr< QgsAbstractFeatureSource > mSource
Layer's feature source.
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.
QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &context) override
Returns list of label features (they are owned by the provider and thus deleted on its destruction)
QgsFeatureRenderer * mRenderer
void init()
initialization method - called from constructors
void drawLabel(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw this label at the position determined by the labeling engine.
void drawLabelBackground(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw the background for the specified label.
Represents a vector layer which manages a vector based data sets.
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
QgsFeatureId featureId() const
Returns the unique ID of the feature.
Layer * layer()
Returns the layer that feature belongs to.
QgsLabelFeature * feature()
Returns the parent feature.
LabelPosition is a candidate feature label position.
double getAlpha() const
Returns the angle to rotate text (in rad).
Quadrant getQuadrant() const
bool conflictsWithObstacle() const
Returns whether the position is marked as conflicting with an obstacle feature.
LabelPosition * nextPart() const
Returns the next part of this label position (i.e.
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
double getX(int i=0) const
Returns the down-left x coordinate.
double getY(int i=0) const
Returns the down-left y coordinate.
QgsAbstractLabelProvider * provider() const
Returns pointer to the associated provider.
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)
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 QgsDebugMsgLevel(str, level)
QList< QgsSymbol * > QgsSymbolList
const QgsCoordinateReferenceSystem & crs
Utility class for identifying a unique vertex within a geometry.