QGIS API Documentation  2.99.0-Master (5d67572)
qgspallabeling.h
Go to the documentation of this file.
1 /***************************************************************************
2  qgspallabeling.h
3  Smart labeling for vector layers
4  -------------------
5  begin : June 2009
6  copyright : (C) Martin Dobias
7  email : wonder dot sk at gmail dot com
8 
9  ***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
18 //Note: although this file is in the core library, it is not part of the stable API
19 //and might change at any time!
20 
21 #ifndef QGSPALLABELING_H
22 #define QGSPALLABELING_H
23 
24 #include "qgis_core.h"
25 #include "qgis_sip.h"
26 #include "qgis.h"
27 #include <QString>
28 #include <QFont>
29 #include <QFontDatabase>
30 #include <QColor>
31 #include <QHash>
32 #include <QList>
33 #include <QPainter>
34 #include <QRectF>
35 #include <QMap>
36 #include "qgsfeature.h"
37 #include "qgsgeometry.h"
38 #include "qgsfields.h"
40 #include "qgspointxy.h"
41 #include "qgsmapunitscale.h"
42 #include "qgsstringutils.h"
43 #include "qgstextrenderer.h"
44 #include "qgspropertycollection.h"
45 
46 namespace pal SIP_SKIP
47 {
48  class Pal;
49  class Layer;
50  class LabelPosition;
51 }
52 
54 class QgsRectangle;
55 class QgsMapToPixel;
56 class QgsFeature;
58 class QgsVectorLayer;
59 class QgsExpression;
60 class QFontMetricsF;
61 class QPainter;
62 class QPicture;
63 class QgsGeometry;
65 class QgsLabelSearchTree;
66 class QgsMapSettings;
67 class QgsLabelFeature;
68 class QgsLabelingEngine;
71 class QgsDxfExport;
74 
75 
80 class CORE_EXPORT QgsLabelPosition
81 {
82  public:
83  QgsLabelPosition( int id, double r, const QVector< QgsPointXY > &corners, const QgsRectangle &rect, double w, double h, const QString &layer, const QString &labeltext, const QFont &labelfont, bool upside_down, bool diagram = false, bool pinned = false, const QString &providerId = QString() )
84  : featureId( id )
85  , rotation( r )
86  , cornerPoints( corners )
87  , labelRect( rect )
88  , width( w )
89  , height( h )
90  , layerID( layer )
91  , labelText( labeltext )
92  , labelFont( labelfont )
93  , upsideDown( upside_down )
94  , isDiagram( diagram )
95  , isPinned( pinned )
96  , providerID( providerId )
97  {}
99  {}
100 
101  int featureId = -1;
102  double rotation = 0;
103  QVector< QgsPointXY > cornerPoints;
105  double width = 0;
106  double height = 0;
107  QString layerID;
108  QString labelText;
109  QFont labelFont;
110  bool upsideDown = false;
111  bool isDiagram = false;
112  bool isPinned = false;
114  QString providerID;
115 };
116 
117 
122 class CORE_EXPORT QgsPalLayerSettings
123 {
124  public:
128 
130  QgsPalLayerSettings &operator=( const QgsPalLayerSettings &s );
131 
135  //TODO QGIS 3.0 - move to QgsLabelingEngine
137  {
146  };
147 
149  //TODO QGIS 3.0 - move to QgsLabelingEngine
151  {
164  };
165 
170  //TODO QGIS 3.0 - move to QgsLabelingEngine
172  {
175  };
176 
180  //TODO QGIS 3.0 - move to QgsLabelingEngine, rename to LinePlacementFlag, use Q_DECLARE_FLAGS to make
181  //LinePlacementFlags type, and replace use of pal::LineArrangementFlag
183  {
184  OnLine = 1,
185  AboveLine = 2,
188  BelowLine = 4,
191  MapOrientation = 8,
194  };
195 
197  {
207  };
208 
210  {
213  ShowAll
214  };
215 
217  {
220  SymbolBelow
221  };
222 
224  {
225  MultiLeft = 0,
228  MultiFollowPlacement
230  };
231 
236  //TODO QGIS 3.0 - Move to QgsLabelingEngine
238  {
239  PolygonInterior,
241  PolygonBoundary,
243  PolygonWhole
247  };
248 
250  enum Property
251  {
252  // text style
253  Size = 0,
254  Bold = 1,
255  Italic = 2,
256  Underline = 3,
257  Color = 4,
258  Strikeout = 5,
259  Family = 6,
260  FontStyle = 21,
261  FontSizeUnit = 22,
262  FontTransp = 18,
263  FontOpacity = 92,
264  FontCase = 27,
265  FontLetterSpacing = 28,
266  FontWordSpacing = 29,
267  FontBlendMode = 30,
268 
269  // text formatting
270  MultiLineWrapChar = 31,
271  MultiLineHeight = 32,
272  MultiLineAlignment = 33,
273  DirSymbDraw = 34,
274  DirSymbLeft = 35,
275  DirSymbRight = 36,
276  DirSymbPlacement = 37,
277  DirSymbReverse = 38,
278  NumFormat = 39,
279  NumDecimals = 40,
280  NumPlusSign = 41,
281 
282  // text buffer
283  BufferDraw = 42,
284  BufferSize = 7,
285  BufferUnit = 43,
286  BufferColor = 8,
287  BufferTransp = 19,
288  BufferOpacity = 94,
289  BufferJoinStyle = 44,
290  BufferBlendMode = 45,
291 
292  // background
293  ShapeDraw = 46,
294  ShapeKind = 47,
295  ShapeSVGFile = 48,
296  ShapeSizeType = 49,
297  ShapeSizeX = 50,
298  ShapeSizeY = 85,
299  ShapeSizeUnits = 51,
300  ShapeRotationType = 52,
301  ShapeRotation = 53,
302  ShapeOffset = 54,
303  ShapeOffsetUnits = 55,
304  ShapeRadii = 56,
305  ShapeRadiiUnits = 57,
306  ShapeTransparency = 63,
307  ShapeOpacity = 93,
308  ShapeBlendMode = 64,
309  ShapeFillColor = 58,
310  ShapeStrokeColor = 59,
311  ShapeStrokeWidth = 60,
312  ShapeStrokeWidthUnits = 61,
313  ShapeJoinStyle = 62,
314 
315  // drop shadow
316  ShadowDraw = 65,
317  ShadowUnder = 66,
318  ShadowOffsetAngle = 67,
319  ShadowOffsetDist = 68,
320  ShadowOffsetUnits = 69,
321  ShadowRadius = 70,
322  ShadowRadiusUnits = 71,
323  ShadowTransparency = 72,
324  ShadowOpacity = 95,
325  ShadowScale = 73,
326  ShadowColor = 74,
327  ShadowBlendMode = 75,
328 
329  // placement
330  CentroidWhole = 76,
331  OffsetQuad = 77,
332  OffsetXY = 78,
333  OffsetUnits = 80,
334  LabelDistance = 13,
335  DistanceUnits = 81,
336  OffsetRotation = 82,
337  CurvedCharAngleInOut = 83,
338  // (data defined only)
339  PositionX = 9,
340  PositionY = 10,
341  Hali = 11,
342  Vali = 12,
343  Rotation = 14,
344  LabelRotation = 96,
345  RepeatDistance = 84,
346  RepeatDistanceUnit = 86,
347  Priority = 87,
348  PredefinedPositionOrder = 91,
349 
350  // rendering
351  ScaleVisibility = 23,
352  MinScale = 16,
353  MinimumScale = 97,
354  MaxScale = 17,
355  MaximumScale = 98,
356  FontLimitPixel = 24,
357  FontMinPixel = 25,
358  FontMaxPixel = 26,
359  IsObstacle = 88,
360  ObstacleFactor = 89,
361  ZIndex = 90,
362 
363  // (data defined only)
364  Show = 15,
365  AlwaysShow = 20
366  };
367 
372  static const QgsPropertiesDefinition &propertyDefinitions();
373 
383 
384  //-- text style
385 
391  QString fieldName;
392 
398 
402  QgsExpression *getLabelExpression();
403 
405 
410 
411  //-- text formatting
412 
417  QString wrapChar;
418 
421 
433 
440 
447 
453 
456 
464 
470  int decimals;
471 
477  bool plusSign;
478 
479  //-- placement
480 
482  unsigned int placementFlags;
483 
489 
496 
503  QVector< PredefinedPointPosition > predefinedPositionOrder SIP_SKIP;
504 
509 
515  double dist;
516 
523 
530 
533 
540 
547 
554 
559 
566  double xOffset;
567 
574  double yOffset;
575 
583 
591 
593  double angleOffset;
594 
597 
603 
609 
614  int priority;
615 
616  //-- rendering
617 
624 
635  double maximumScale;
636 
647  double minimumScale;
648 
655 
662 
669 
672 
674  UpsideDownLabels upsidedownLabels = Upright;
675 
681 
687 
693 
700 
705 
711  bool obstacle;
712 
720 
727 
729  double zIndex;
730 
731  // called from register feature hook
732  void calculateLabelSize( const QFontMetricsF *fm, QString text, double &labelX, double &labelY, QgsFeature *f = nullptr, QgsRenderContext *context = nullptr );
733 
747  void registerFeature( QgsFeature &f, QgsRenderContext &context,
748  QgsLabelFeature **labelFeature SIP_PYARGREMOVE = nullptr,
749  QgsGeometry obstacleGeometry SIP_PYARGREMOVE = QgsGeometry() );
750 
755  void readXml( QDomElement &elem, const QgsReadWriteContext &context );
756 
761  QDomElement writeXml( QDomDocument &doc, const QgsReadWriteContext &context );
762 
768  QgsPropertyCollection &dataDefinedProperties() { return mDataDefinedProperties; }
769 
776  const QgsPropertyCollection &dataDefinedProperties() const SIP_SKIP { return mDataDefinedProperties; }
777 
784  void setDataDefinedProperties( const QgsPropertyCollection &collection ) { mDataDefinedProperties = collection; }
785 
791  const QgsTextFormat &format() const { return mFormat; }
792 
799  void setFormat( const QgsTextFormat &format ) { mFormat = format; }
800 
801  // temporary stuff: set when layer gets prepared or labeled
802  QgsFeature *mCurFeat = nullptr;
805  const QgsMapToPixel *xform = nullptr;
807 
811  int mFeaturesToLabel = 0; // total features that will probably be labeled, may be less (figured before PAL)
812  int mFeatsSendingToPal = 0; // total features tested for sending into PAL (relative to maxNumLabels)
813  int mFeatsRegPal = 0; // number of features registered in PAL, when using limitNumLabels
814 
815  private:
816 
817  friend class QgsVectorLayer; // to allow calling readFromLayerCustomProperties()
818 
823  void readFromLayerCustomProperties( QgsVectorLayer *layer );
824 
828  void readOldDataDefinedPropertyMap( QgsVectorLayer *layer, QDomElement *parentElem );
829 
833  void readOldDataDefinedProperty( QgsVectorLayer *layer, QgsPalLayerSettings::Property p );
834 
835  enum DataDefinedValueType
836  {
837  DDBool,
838  DDInt,
839  DDIntPos,
840  DDDouble,
841  DDDoublePos,
842  DDRotation180,
843  DDOpacity,
844  DDString,
845  DDUnits,
846  DDColor,
847  DDJoinStyle,
848  DDBlendMode,
849  DDPointF
850  };
851 
852  // convenience data defined evaluation function
853  bool dataDefinedValEval( DataDefinedValueType valType,
855  QVariant &exprVal, QgsExpressionContext &context, const QVariant &originalValue = QVariant() );
856 
857  void parseTextStyle( QFont &labelFont,
858  QgsUnitTypes::RenderUnit fontunits,
859  QgsRenderContext &context );
860 
861  void parseTextBuffer( QgsRenderContext &context );
862 
863  void parseTextFormatting( QgsRenderContext &context );
864 
865  void parseShapeBackground( QgsRenderContext &context );
866 
867  void parseDropShadow( QgsRenderContext &context );
868 
872  bool checkMinimumSizeMM( const QgsRenderContext &ct, const QgsGeometry &geom, double minSize ) const;
873 
877  void registerObstacleFeature( QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **obstacleFeature, const QgsGeometry &obstacleGeometry = QgsGeometry() );
878 
879  QMap<Property, QVariant> dataDefinedValues;
880 
882  QgsPropertyCollection mDataDefinedProperties;
883 
884  QgsExpression *expression = nullptr;
885 
886  QFontDatabase mFontDB;
887 
888  QgsTextFormat mFormat;
889 
890  static const QVector< PredefinedPointPosition > DEFAULT_PLACEMENT_ORDER;
891 
892  static void initPropertyDefinitions();
893 
895  static QgsPropertiesDefinition sPropertyDefinitions;
896 
897 };
898 
902 class CORE_EXPORT QgsLabelCandidate
903 {
904  public:
905  QgsLabelCandidate( const QRectF &r, double c ): rect( r ), cost( c ) {}
906 
907  QRectF rect;
908  double cost;
909 };
910 
911 
912 
913 
919 class CORE_EXPORT QgsLabelingResults
920 {
921  public:
924 
926  QgsLabelingResults( const QgsLabelingResults & ) = delete;
928  QgsLabelingResults &operator=( const QgsLabelingResults &rh ) = delete;
929 
931  QList<QgsLabelPosition> labelsAtPosition( const QgsPointXY &p ) const;
933  QList<QgsLabelPosition> labelsWithinRect( const QgsRectangle &r ) const;
934 
935  private:
936 #ifdef SIP_RUN
938 #endif
939 
940  QgsLabelSearchTree *mLabelSearchTree = nullptr;
941 
942  friend class QgsPalLabeling;
945 };
946 
951 class CORE_EXPORT QgsPalLabeling
952 {
953  public:
954 
959  static bool staticWillUseLayer( QgsVectorLayer *layer );
960 
962  static void drawLabelCandidateRect( pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList<QgsLabelCandidate> *candidates = nullptr ) SIP_SKIP;
963 
973  static QgsGeometry prepareGeometry( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry = QgsGeometry() ) SIP_FACTORY;
974 
984  static bool geometryRequiresPreparation( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry = QgsGeometry() );
985 
994  static QStringList splitToLines( const QString &text, const QString &wrapCharacter );
995 
1004  static QStringList splitToGraphemes( const QString &text );
1005 
1006  private:
1008  static void dataDefinedTextStyle( QgsPalLayerSettings &tmpLyr,
1009  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1010 
1012  static void dataDefinedTextFormatting( QgsPalLayerSettings &tmpLyr,
1013  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1014 
1016  static void dataDefinedTextBuffer( QgsPalLayerSettings &tmpLyr,
1017  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1018 
1020  static void dataDefinedShapeBackground( QgsPalLayerSettings &tmpLyr,
1021  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1022 
1024  static void dataDefinedDropShadow( QgsPalLayerSettings &tmpLyr,
1025  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1026 
1027  friend class QgsVectorLayerLabelProvider; // to allow calling the static methods above
1028  friend class QgsDxfExport; // to allow calling the static methods above
1029 
1038  static bool checkMinimumSizeMM( const QgsRenderContext &context, const QgsGeometry &geom, double minSize );
1039 
1040  friend class QgsPalLayerSettings;
1041 };
1042 
1043 #endif // QGSPALLABELING_H
Label below point, slightly right of center.
QgsRectangle labelRect
double xOffset
Horizontal offset of label.
The class is used as a container of context for various read/write operations on other objects...
A rectangle specified with double values.
Definition: qgsrectangle.h:39
Label on bottom-left of point.
double maxCurvedCharAngleOut
Maximum angle between outside curved label characters (valid range -20.0 to -95.0) ...
double maximumScale
The maximum map scale (i.e.
QString leftDirectionSymbol
String to use for left direction arrows.
QgsUnitTypes::RenderUnit repeatDistanceUnit
Units for repeating labels for a single feature.
double angleOffset
Label rotation, in degrees clockwise.
bool formatNumbers
Set to true to format numeric label text as numbers (e.g.
A class to query the labeling structure at a given point (small wraper around pal RTree class) ...
double obstacleFactor
Obstacle factor, where 1.0 = default, < 1.0 more likely to be covered by labels, 1.0 less likely to be covered
Label on top-left of point.
QgsLabelCandidate(const QRectF &r, double c)
PredefinedPointPosition
Positions for labels when using the QgsPalLabeling::OrderedPositionsAroundPoint placement mode...
A class to represent a 2D point.
Definition: qgspointxy.h:43
bool obstacle
True if features for layer are obstacles to labels of other layers.
int decimals
Number of decimal places to show for numeric labels.
double repeatDistance
Distance for repeating labels for a single feature.
Candidates are placed in predefined positions around a point. Preference is given to positions with g...
QuadrantPosition quadOffset
Sets the quadrant in which to offset labels from feature.
QgsUnitTypes::RenderUnit offsetUnits
Units for offsets of label.
double yOffset
Vertical offset of label.
Class that adds extra information to QgsLabelFeature for text labels.
Container of fields for a vector layer.
Definition: qgsfields.h:42
Label on top of point, slightly right of center.
bool addDirectionSymbol
If true, &#39;<&#39; or &#39;>&#39; (or custom strings set via leftDirectionSymbol and rightDirectionSymbol) will be ...
The QgsVectorLayerLabelProvider class implements a label provider for vector layers.
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:94
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 ...
QgsMapUnitScale repeatDistanceMapUnitScale
Map unit scale for repeating labels for a single feature.
MultiLineAlign multilineAlign
Horizontal alignment of multi-line labels.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:62
double maxCurvedCharAngleIn
Maximum angle between inside curved label characters (valid range 20.0 to 60.0).
QgsCoordinateTransform ct
bool reverseDirectionSymbol
True if direction symbols should be reversed.
void setFormat(const QgsTextFormat &format)
Sets the label text formatting settings, e.g., font settings, buffer settings, etc.
double zIndex
Z-Index of label, where labels with a higher z-index are rendered on top of labels with a lower z-ind...
QgsStringReplacementCollection substitutions
Substitution collection for automatic text substitution with labels.
Arranges candidates following the curvature of a line feature. Applies to line layers only...
The QgsMapSettings class contains configuration for rendering of the map.
Place direction symbols on left/right of label.
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:36
Property
Data definable properties.
ObstacleType obstacleType
Controls how features act as obstacles for labels.
const QgsPropertyCollection & dataDefinedProperties() const
Returns a reference to the label&#39;s property collection, used for data defined overrides.
bool displayAll
If true, all features will be labelled even when overlaps occur.
Label on left of point.
Offset distance applies from point geometry.
void setDataDefinedProperties(const QgsPropertyCollection &collection)
Sets the label&#39;s property collection, used for data defined overrides.
int fontMaxPixelSize
Maximum pixel size for showing rendered map unit labels (1 - 10000).
#define SIP_SKIP
Definition: qgis_sip.h:119
The QgsVectorLayerDiagramProvider class implements support for diagrams within the labeling engine...
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QVector< QgsPointXY > cornerPoints
Arranges candidates in a circle around a point (or centroid of a polygon). Applies to point or polygo...
Upside-down labels (90 <= angle < 270) are shown upright.
OffsetType
Behavior modifier for label offset and distance, only applies in some label placement modes...
#define SIP_FACTORY
Definition: qgis_sip.h:69
Offset distance applies from rendered symbol bounds.
const QgsTextFormat & format() const
Returns the label text formatting settings, e.g., font settings, buffer settings, etc...
QMap< int, QgsPropertyDefinition > QgsPropertiesDefinition
Definition of available properties.
int maxNumLabels
The maximum number of labels which should be drawn for this layer.
Place direction symbols on above label.
Stores the settings for rendering of all diagrams for a layer.
bool plusSign
Whether &#39;+&#39; signs should be prepended to positive numeric labels.
unsigned int placementFlags
QString wrapChar
Wrapping character string.
Placement
Placement modes which determine how label candidates are generated for a feature. ...
#define SIP_PYARGREMOVE
Definition: qgis_sip.h:139
QString rightDirectionSymbol
String to use for right direction arrows.
The QgsLabelingEngine class provides map labeling functionality.
bool preserveRotation
True if label rotation should be preserved during label pin/unpin operations.
Arranges candidates over a point (or centroid of a polygon), or at a preset offset from the point...
Contains information about the context of a rendering operation.
bool centroidWhole
True if feature centroid should be calculated from the whole feature, or false if only the visible pa...
bool scaleVisibility
Set to true to limit label visibility to a range of scales.
The QgsLabelFeature class describes a feature that should be used within the labeling engine...
QgsGeometry extentGeom
QgsMapUnitScale distMapUnitScale
Map unit scale for label feature distance.
Struct for storing maximum and minimum scales for measurements in map units.
bool fitInPolygonOnly
True if only labels which completely fit within a polygon are allowed.
A collection of string replacements (specified using QgsStringReplacement objects).
OffsetType offsetType
Offset type for layer (only applies in certain placement modes)
double dist
Distance from feature to the label.
bool useSubstitutions
True if substitutions should be applied.
Label below point, slightly left of center.
Class for doing transforms between two map coordinate systems.
LabelPosition is a candidate feature label position.
Definition: labelposition.h:55
Label on top of point, slightly left of center.
A grouped map of multiple QgsProperty objects, each referenced by a integer key value.
Label on right of point.
bool limitNumLabels
True if the number of labels drawn should be limited.
bool isExpression
True if this label is made from a expression string, e.g., FieldName || &#39;mm&#39;.
Class that stores computed placement from labeling engine.
LinePlacementFlags
Line placement flags, which control how candidates are generated for a linear feature.
Show upside down when rotation is layer- or data-defined.
Container for all settings relating to text rendering.
bool centroidInside
True if centroid positioned labels must be placed inside their corresponding feature polygon...
QgsLabelPosition(int id, double r, const QVector< QgsPointXY > &corners, const QgsRectangle &rect, double w, double h, const QString &layer, const QString &labeltext, const QFont &labelfont, bool upside_down, bool diagram=false, bool pinned=false, const QString &providerId=QString())
Represents a vector layer which manages a vector based data sets.
double minFeatureSize
Minimum feature size (in millimeters) for a feature to be labelled.
int fontMinPixelSize
Minimum pixel size for showing rendered map unit labels (1 - 1000).
int priority
Label priority.
bool labelPerPart
True if every part of a multi-part feature should be labeled.
QgsUnitTypes::RenderUnit distUnits
Units the distance from feature to the label.
QgsMapUnitScale labelOffsetMapUnitScale
Map unit scale for label offset.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:100
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label&#39;s property collection, used for data defined overrides.
double minimumScale
The minimum map scale (i.e.
QString fieldName
Name of field (or an expression) to use for label text.
bool fontLimitPixelSize
True if label sizes should be limited by pixel size.
ObstacleType
Valid obstacle types, which affect how features within the layer will act as obstacles for labels...
DirectionSymbols placeDirectionSymbol
Placement option for direction symbols.
Arranges candidates scattered throughout a polygon feature. Candidates are rotated to respect the pol...