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