| QGIS API Documentation
    3.16.0-Hannover (43b64b13f3)
    | 
 
 
 
Go to the documentation of this file.
   33 static bool _palIsCanceled( 
void *ctx )
 
   35   return ( 
reinterpret_cast< QgsRenderContext * 
>( ctx ) )->renderingStopped();
 
   48       : mMapSettings( mapSettings )
 
   60       QStringList layerIds = mMapSettings.
layerIds();
 
   63       if ( layer1Pos != layer2Pos && layer1Pos >= 0 && layer2Pos >= 0 )
 
   64         return layer1Pos > layer2Pos; 
 
   67       return lf1->
size().width() * lf1->
size().height() > lf2->
size().width() * lf2->
size().height();
 
   98   QList< QgsMapLayer * > layers;
 
  101   QList< QgsAbstractLabelProvider * > providersByZ = 
mProviders;
 
  102   std::sort( providersByZ.begin(), providersByZ.end(),
 
  105     const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
 
  106     const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
 
  108     if ( providerA && providerB )
 
  110       return providerA->settings().zIndex < providerB->settings().zIndex ;
 
  115   QList< QgsAbstractLabelProvider * > subProvidersByZ = mSubProviders;
 
  116   std::sort( subProvidersByZ.begin(), subProvidersByZ.end(),
 
  119     const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
 
  120     const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
 
  122     if ( providerA && providerB )
 
  124       return providerA->settings().zIndex < providerB->settings().zIndex ;
 
  131     if ( provider->layer() && !layers.contains( provider->layer() ) )
 
  132       layers << provider->layer();
 
  136     if ( provider->layer() && !layers.contains( provider->layer() ) )
 
  137       layers << provider->layer();
 
  147   QList< QgsAbstractLabelProvider * > providersByZ = 
mProviders;
 
  148   std::sort( providersByZ.begin(), providersByZ.end(),
 
  151     const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
 
  152     const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
 
  154     if ( providerA && providerB )
 
  156       return providerA->settings().zIndex < providerB->settings().zIndex ;
 
  161   QList< QgsAbstractLabelProvider * > subProvidersByZ = mSubProviders;
 
  162   std::sort( subProvidersByZ.begin(), subProvidersByZ.end(),
 
  165     const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
 
  166     const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
 
  168     if ( providerA && providerB )
 
  170       return providerA->settings().zIndex < providerB->settings().zIndex ;
 
  177     if ( !layers.contains( provider->layerId() ) )
 
  178       layers << provider->layerId();
 
  182     if ( !layers.contains( provider->layerId() ) )
 
  183       layers << provider->layerId();
 
  205   QgsAbstractLabelProvider::Flags flags = provider->
flags();
 
  242   const QList<QgsLabelFeature *> features = provider->
labelFeatures( context );
 
  250     catch ( std::exception &e )
 
  253       QgsDebugMsgLevel( QStringLiteral( 
"Ignoring feature %1 due PAL exception:" ).arg( feature->id() ) + QString::fromLatin1( e.what() ), 4 );
 
  271   mPal = qgis::make_unique< pal::Pal >();
 
  282     std::unique_ptr< QgsExpressionContextScopePopper > layerScopePopper;
 
  293   Q_ASSERT( 
mPal.get() );
 
  298   QPainter *painter = context.
painter();
 
  302   visiblePoly.append( visiblePoly.at( 0 ) ); 
 
  311     mapBoundaryGeom = mapBoundaryGeom.
difference( region.geometry );
 
  320     properties.insert( QStringLiteral( 
"style" ), QStringLiteral( 
"no" ) );
 
  321     properties.insert( QStringLiteral( 
"style_border" ), QStringLiteral( 
"solid" ) );
 
  322     properties.insert( QStringLiteral( 
"color_border" ), QStringLiteral( 
"#0000ff" ) );
 
  323     properties.insert( QStringLiteral( 
"width_border" ), QStringLiteral( 
"0.3" ) );
 
  324     properties.insert( QStringLiteral( 
"joinstyle" ), QStringLiteral( 
"miter" ) );
 
  326     boundarySymbol->startRender( context );
 
  327     boundarySymbol->renderFeature( f, context );
 
  328     boundarySymbol->stopRender( context );
 
  341   mPal->registerCancellationCallback( &_palIsCanceled, 
reinterpret_cast< void * 
>( &context ) );
 
  349     mProblem = 
mPal->extractProblem( extent, mapBoundaryGeom );
 
  351   catch ( std::exception &e )
 
  354     QgsDebugMsgLevel( 
"PAL EXCEPTION :-( " + QString::fromLatin1( e.what() ), 4 );
 
  380     painter->setBrush( Qt::NoBrush );
 
  381     for ( 
int i = 0; i < static_cast< int >( 
mProblem->featureCount() ); i++ )
 
  383       for ( 
int j = 0; j < 
mProblem->featureCandidateCount( i ); j++ )
 
  398   QgsDebugMsgLevel( QStringLiteral( 
"LABELING work:  %1 ms ... labels# %2" ).arg( t.elapsed() ).arg( 
mLabels.size() ), 4 );
 
  409   QPainter *painter = context.
painter();
 
  414     if ( !layerId.isEmpty() && provider->layerId() != layerId )
 
  420     provider->startRender( context );
 
  424   std::unique_ptr< QgsExpressionContextScopePopper > symbolScopePopper = qgis::make_unique< QgsExpressionContextScopePopper >( context.
expressionContext(), symbolScope );
 
  504   symbolScopePopper.reset();
 
  509     if ( !layerId.isEmpty() && provider->layerId() != layerId )
 
  512     provider->stopRender( context );
 
  516   painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
 
  518   QgsDebugMsgLevel( QStringLiteral( 
"LABELING draw:  %1 ms" ).arg( t.elapsed() ), 4 );
 
  614   : mLayerId( layer ? layer->id() : QString() )
 
  616   , mProviderId( providerId )
 
  617   , mFlags( DrawLabels )
 
  639     subProvider->startRender( context );
 
  648     subProvider->stopRender( context );
 
  658   QStringList predefinedOrderString;
 
  659   const auto constPositions = positions;
 
  665         predefinedOrderString << QStringLiteral( 
"TL" );
 
  668         predefinedOrderString << QStringLiteral( 
"TSL" );
 
  671         predefinedOrderString << QStringLiteral( 
"T" );
 
  674         predefinedOrderString << QStringLiteral( 
"TSR" );
 
  677         predefinedOrderString << QStringLiteral( 
"TR" );
 
  680         predefinedOrderString << QStringLiteral( 
"L" );
 
  683         predefinedOrderString << QStringLiteral( 
"R" );
 
  686         predefinedOrderString << QStringLiteral( 
"BL" );
 
  689         predefinedOrderString << QStringLiteral( 
"BSL" );
 
  692         predefinedOrderString << QStringLiteral( 
"B" );
 
  695         predefinedOrderString << QStringLiteral( 
"BSR" );
 
  698         predefinedOrderString << QStringLiteral( 
"BR" );
 
  702   return predefinedOrderString.join( 
',' );
 
  707   QVector<QgsPalLayerSettings::PredefinedPointPosition> result;
 
  708   const QStringList predefinedOrderList = positionString.split( 
',' );
 
  709   result.reserve( predefinedOrderList.size() );
 
  710   for ( 
const QString &position : predefinedOrderList )
 
  712     QString cleaned = position.trimmed().toUpper();
 
  713     if ( cleaned == QLatin1String( 
"TL" ) )
 
  715     else if ( cleaned == QLatin1String( 
"TSL" ) )
 
  717     else if ( cleaned == QLatin1String( 
"T" ) )
 
  719     else if ( cleaned == QLatin1String( 
"TSR" ) )
 
  721     else if ( cleaned == QLatin1String( 
"TR" ) )
 
  723     else if ( cleaned == QLatin1String( 
"L" ) )
 
  725     else if ( cleaned == QLatin1String( 
"R" ) )
 
  727     else if ( cleaned == QLatin1String( 
"BL" ) )
 
  729     else if ( cleaned == QLatin1String( 
"BSL" ) )
 
  731     else if ( cleaned == QLatin1String( 
"B" ) )
 
  733     else if ( cleaned == QLatin1String( 
"BSR" ) )
 
  735     else if ( cleaned == QLatin1String( 
"BR" ) )
 
  745     parts << QStringLiteral( 
"OL" );
 
  747     parts << QStringLiteral( 
"AL" );
 
  749     parts << QStringLiteral( 
"BL" );
 
  751     parts << QStringLiteral( 
"LO" );
 
  752   return parts.join( 
',' );
 
  757   QgsLabeling::LinePlacementFlags flags = QgsLabeling::LinePlacementFlags();
 
  758   const QStringList flagList = 
string.split( 
',' );
 
  759   bool foundLineOrientationFlag = 
false;
 
  760   for ( 
const QString &flag : flagList )
 
  762     QString cleaned = flag.trimmed().toUpper();
 
  763     if ( cleaned == QLatin1String( 
"OL" ) )
 
  765     else if ( cleaned == QLatin1String( 
"AL" ) )
 
  767     else if ( cleaned == QLatin1String( 
"BL" ) )
 
  769     else if ( cleaned == QLatin1String( 
"LO" ) )
 
  770       foundLineOrientationFlag = 
true;
 
  772   if ( !foundLineOrientationFlag )
 
  
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
void addProvider(QgsAbstractLabelProvider *provider)
Add provider of label features. Takes ownership of the provider.
virtual void drawLabel(QgsRenderContext &context, pal::LabelPosition *label) const =0
Draw this label at the position determined by the labeling engine.
RAII class to pop scope from an expression context on destruction.
virtual void stopRender(QgsRenderContext &context)
To be called after rendering is complete.
void processProvider(QgsAbstractLabelProvider *provider, QgsRenderContext &context, pal::Pal &p)
void setUpsidedownLabels(UpsideDownLabels ud)
Sets how upside down labels will be handled within the layer.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
QgsAbstractLabelProvider * provider() const
Returns provider of this instance.
QString layerId() const
Returns ID of associated layer, or empty string if no layer is associated with the provider.
std::unique_ptr< pal::Pal > mPal
QgsExpressionContext & expressionContext()
Gets the expression context.
QgsPalLayerSettings::UpsideDownLabels upsidedownLabels() const
How to handle labels that would be upside down.
QStringList participatingLayerIds() const
Returns a list of layer IDs for layers with providers in the engine.
void drawLabels(QgsRenderContext &context, const QString &layerId=QString())
Draws labels to the specified render context.
void run(QgsRenderContext &context) override
Runs the labeling job.
static QString encodePredefinedPositionOrder(const QVector< QgsPalLayerSettings::PredefinedPointPosition > &positions)
Encodes an ordered list of predefined point label positions to a string.
#define QgsDebugMsgLevel(str, level)
void setCentroidInside(bool forceInside)
Sets whether labels placed at the centroid of features within the layer are forced to be placed insid...
@ DrawCandidates
Whether to draw rectangles of generated candidates (good for debugging)
QList< QgsAbstractLabelProvider * > mProviders
List of providers (the are owned by the labeling engine)
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
void removeProvider(QgsAbstractLabelProvider *provider)
Remove provider if the provider's initialization failed. Provider instance is deleted.
@ DrawLabels
Whether the labels should be rendered.
LabelPosition is a candidate feature label position.
MapOrientation
Signifies that the AboveLine and BelowLine flags should respect the map's orientation rather than the...
AboveLine
Labels can be placed above a line feature.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
QgsAbstractLabelProvider * provider() const
Returns pointer to the associated provider.
Class that stores computed placement from labeling engine.
@ MiddleRight
Label on right of point.
QgsLabelObstacleSettings::ObstacleType obstacleType() const
How the feature geometries will work as obstacles.
bool operator()(pal::LabelPosition *lp1, pal::LabelPosition *lp2) const
double convertToMapUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
@ TopRight
Label on top-right of point.
QList< pal::LabelPosition * > mUnlabeled
Contains information about the context of a rendering operation.
OperationResult rotate(double rotation, const QgsPointXY ¢er)
Rotate this geometry around the Z axis.
@ RenderMillimeters
Millimeters.
QgsLabelSorter(const QgsMapSettings &mapSettings)
PlacementEngineVersion placementVersion() const
Returns the placement engine version, which dictates how the label placement problem is solved.
QgsLabelingEngine()
Construct the labeling engine with default settings.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
QList< QgsAbstractLabelProvider * > mSubProviders
virtual void drawUnplacedLabel(QgsRenderContext &context, pal::LabelPosition *label) const
Draw an unplaced label.
void setMapSettings(const QgsMapSettings &mapSettings)
Associate map settings instance.
@ TopSlightlyRight
Label on top of point, slightly right of center.
Flags flags() const
Gets flags of the labeling engine.
A rectangle specified with double values.
double priority() const
Default priority of labels (may be overridden by individual labels)
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
static QVector< QgsPalLayerSettings::PredefinedPointPosition > decodePredefinedPositionOrder(const QString &positionString)
Decodes a string to an ordered list of predefined point label positions.
@ TopMiddle
Label directly above point.
QgsPalLayerSettings::Placement placement() const
What placement strategy to use for the labels.
@ BottomMiddle
Label directly below point.
Layer * addLayer(QgsAbstractLabelProvider *provider, const QString &layerName, QgsPalLayerSettings::Placement arrangement, double defaultPriority, bool active, bool toLabel, bool displayAll=false)
add a new layer
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
@ MergeConnectedLines
Whether adjacent lines (with the same label text) should be merged.
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
The QgsAbstractLabelProvider class is an interface class.
@ CentroidMustBeInside
Whether location of centroid must be inside of polygons.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
static QString encodeLinePlacementFlags(QgsLabeling::LinePlacementFlags flags)
Encodes line placement flags to a string.
const QgsSymbol * symbol()
Returns the feature symbol associated with this label.
Stores global configuration for labeling engine.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
@ TopSlightlyLeft
Label on top of point, slightly left of center.
bool testFlag(Flag f) const
Test whether a particular flag is enabled.
@ BottomSlightlyLeft
Label below point, slightly left of center.
void finalize()
Finalizes and cleans up the engine following the rendering of labels for the last layer to be labeled...
void setEngine(const QgsLabelingEngine *engine)
Associate provider with a labeling engine (should be only called internally from QgsLabelingEngine)
QgsStagedRenderLabelingEngine()
Construct the labeling engine with default settings.
virtual QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &context)=0
Returns list of label features (they are owned by the provider and thus deleted on its destruction)
void cleanup()
Cleans up the engine following a call to registerLabels() or solve().
QPolygonF visiblePolygon() const
Returns the visible area as a polygon (may be rotated)
void setMergeConnectedLines(bool merge)
Sets whether connected lines should be merged before labeling.
QString name() const
Name of the layer (for statistics, debugging etc.) - does not need to be unique.
virtual QList< QgsAbstractLabelProvider * > subProviders()
Returns list of child providers - useful if the provider needs to put labels into more layers with di...
@ Upright
Upside-down labels (90 <= angle < 270) are shown upright.
@ MiddleLeft
Label on left of point.
PredefinedPointPosition
Positions for labels when using the QgsPalLabeling::OrderedPositionsAroundPoint placement mode.
void renderLabelsForLayer(QgsRenderContext &context, const QString &layerId)
Renders all the labels which belong only to the layer with matching layerId to the specified render c...
@ ShowDefined
Show upside down when rotation is layer- or data-defined.
QgsFeature feature() const
Returns the original feature associated with this label.
QList< QgsLabelBlockingRegion > labelBlockingRegions() const
Returns the list of regions to avoid placing labels within.
virtual ~QgsLabelingEngine()
Clean up everything (especially the registered providers)
QList< QgsMapLayer * > participatingLayers() const
Returns a list of layers with providers in the engine.
@ BottomSlightlyRight
Label below point, slightly right of center.
Single scope for storing variables and functions for use within a QgsExpressionContext.
virtual void drawLabelBackground(QgsRenderContext &context, pal::LabelPosition *label) const
Draw the background for the specified label.
std::unique_ptr< pal::Problem > mProblem
The QgsLabelingEngine class provides map labeling functionality.
OnLine
Labels can be placed directly over a line feature.
virtual void startRender(QgsRenderContext &context)
To be called before rendering of labels begins.
@ DrawAllLabels
Whether all features will be labelled even though overlaps occur.
QMap< QString, QString > QgsStringMap
@ TopLeft
Label on top-left of point.
QgsDefaultLabelingEngine()
Construct the labeling engine with default settings.
double zIndex() const
Returns the label's z-index.
QgsLabelingResults * takeResults()
Returns pointer to recently computed results and pass the ownership of results to the caller.
void setSymbol(const QgsSymbol *symbol)
Sets the feature symbol associated with this 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.
QSizeF size(double angle=0.0) const
Size of the label (in map units)
A geometry is the spatial representation of a feature.
@ UsePartialCandidates
Whether to use also label candidates that are partially outside of the map view.
Perform transforms between map coordinates and device coordinates.
double maximumPolygonCandidatesPerCmSquared() const
Returns the maximum number of polygon label candidate positions per centimeter squared.
Base class for all map layer types.
void setObstacleType(QgsLabelObstacleSettings::ObstacleType obstacleType)
Sets the obstacle type, which controls how features within the layer act as obstacles for labels.
static QgsGeometry fromRect(const QgsRectangle &rect) SIP_HOLDGIL
Creates a new geometry from a QgsRectangle.
static QgsLabeling::LinePlacementFlags decodeLinePlacementFlags(const QString &string)
Decodes a string to set of line placement flags.
double maximumLineCandidatesPerCm() const
Returns the maximum number of line label candidate positions per centimeter.
std::unique_ptr< QgsLabelingResults > mResults
Resulting labeling layout.
QgsMapSettings mMapSettings
Associated map settings instance.
A set of features which influence the labeling process.
Flags flags() const
Flags associated with the provider.
@ BottomRight
Label on bottom right of point.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Label blocking region (in map coordinates and CRS).
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
void solve(QgsRenderContext &context)
Solves the label problem.
static QgsFillSymbol * createSimple(const QgsStringMap &properties)
Create a fill symbol with one symbol layer: SimpleFill with specified properties.
The QgsLabelFeature class describes a feature that should be used within the labeling engine.
void run(QgsRenderContext &context) override
Runs the labeling job.
QgsGeometry labelBoundaryGeometry() const
Returns the label boundary geometry, which restricts where in the rendered map labels are permitted t...
QPainter * painter()
Returns the destination QPainter for the render operation.
void registerLabels(QgsRenderContext &context)
Runs the label registration step.
pal::Layer * mLayer
Pointer to PAL layer (assigned when registered to PAL)
The QgsMapSettings class contains configuration for rendering of the map.
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes takes output image size into accou...
QgsLabelFeature * feature()
Returns the parent feature.
@ UseAllLabels
Whether to draw all labels even if there would be collisions.
void setMapRotation(double degrees, double cx, double cy)
Set map rotation in degrees (clockwise)
const QgsMapToPixel & mapToPixel() const
BelowLine
Labels can be placed below a line feature.
QgsGeometry difference(const QgsGeometry &geometry) const
Returns a geometry representing the points making up this geometry that do not make up other.
Helper class for sorting labels into correct draw order.
@ DrawUnplacedLabels
Whether to render unplaced labels as an indicator/warning for users.
QStringList layerIds() const
Gets list of layer IDs for map rendering The layers are stored in the reverse order of how they are r...
@ ShowAll
Show upside down for all labels, including dynamic ones.
QList< pal::LabelPosition * > mLabels
static void drawLabelCandidateRect(pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList< QgsLabelCandidate > *candidates=nullptr)
@ BottomLeft
Label on bottom-left of point.
QgsAbstractLabelProvider(QgsMapLayer *layer, const QString &providerId=QString())
Construct the provider with default values.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
bool registerFeature(QgsLabelFeature *label)
Register a feature in the layer.