QGIS API Documentation  2.99.0-Master (f867b65)
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 
79 class CORE_EXPORT QgsLabelPosition
80 {
81  public:
82  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() )
83  : featureId( id )
84  , rotation( r )
85  , cornerPoints( corners )
86  , labelRect( rect )
87  , width( w )
88  , height( h )
89  , layerID( layer )
90  , labelText( labeltext )
91  , labelFont( labelfont )
92  , upsideDown( upside_down )
93  , isDiagram( diagram )
94  , isPinned( pinned )
95  , providerID( providerId )
96  {}
98  : featureId( -1 )
99  , rotation( 0 )
100  , labelRect( QgsRectangle() )
101  , width( 0 )
102  , height( 0 )
103  , layerID( QLatin1String( "" ) )
104  , labelText( QLatin1String( "" ) )
105  , labelFont( QFont() )
106  , upsideDown( false )
107  , isDiagram( false )
108  , isPinned( false )
109  {}
111  double rotation;
112  QVector< QgsPointXY > cornerPoints;
114  double width;
115  double height;
116  QString layerID;
117  QString labelText;
118  QFont labelFont;
120  bool isDiagram;
121  bool isPinned;
123  QString providerID;
124 };
125 
126 
130 class CORE_EXPORT QgsPalLayerSettings
131 {
132  public:
136 
138  QgsPalLayerSettings &operator=( const QgsPalLayerSettings &s );
139 
142  //TODO QGIS 3.0 - move to QgsLabelingEngine
144  {
153  };
154 
156  //TODO QGIS 3.0 - move to QgsLabelingEngine
158  {
171  };
172 
175  //TODO QGIS 3.0 - move to QgsLabelingEngine
177  {
180  };
181 
184  //TODO QGIS 3.0 - move to QgsLabelingEngine, rename to LinePlacementFlag, use Q_DECLARE_FLAGS to make
185  //LinePlacementFlags type, and replace use of pal::LineArrangementFlag
187  {
188  OnLine = 1,
189  AboveLine = 2,
192  BelowLine = 4,
195  MapOrientation = 8,
198  };
199 
201  {
211  };
212 
214  {
217  ShowAll
218  };
219 
221  {
224  SymbolBelow
225  };
226 
228  {
229  MultiLeft = 0,
232  MultiFollowPlacement
234  };
235 
239  //TODO QGIS 3.0 - Move to QgsLabelingEngine
241  {
242  PolygonInterior,
244  PolygonBoundary,
246  PolygonWhole
250  };
251 
253  enum Property
254  {
255  // text style
256  Size = 0,
257  Bold = 1,
258  Italic = 2,
259  Underline = 3,
260  Color = 4,
261  Strikeout = 5,
262  Family = 6,
263  FontStyle = 21,
264  FontSizeUnit = 22,
265  FontTransp = 18,
266  FontOpacity = 92,
267  FontCase = 27,
268  FontLetterSpacing = 28,
269  FontWordSpacing = 29,
270  FontBlendMode = 30,
271 
272  // text formatting
273  MultiLineWrapChar = 31,
274  MultiLineHeight = 32,
275  MultiLineAlignment = 33,
276  DirSymbDraw = 34,
277  DirSymbLeft = 35,
278  DirSymbRight = 36,
279  DirSymbPlacement = 37,
280  DirSymbReverse = 38,
281  NumFormat = 39,
282  NumDecimals = 40,
283  NumPlusSign = 41,
284 
285  // text buffer
286  BufferDraw = 42,
287  BufferSize = 7,
288  BufferUnit = 43,
289  BufferColor = 8,
290  BufferTransp = 19,
291  BufferOpacity = 94,
292  BufferJoinStyle = 44,
293  BufferBlendMode = 45,
294 
295  // background
296  ShapeDraw = 46,
297  ShapeKind = 47,
298  ShapeSVGFile = 48,
299  ShapeSizeType = 49,
300  ShapeSizeX = 50,
301  ShapeSizeY = 85,
302  ShapeSizeUnits = 51,
303  ShapeRotationType = 52,
304  ShapeRotation = 53,
305  ShapeOffset = 54,
306  ShapeOffsetUnits = 55,
307  ShapeRadii = 56,
308  ShapeRadiiUnits = 57,
309  ShapeTransparency = 63,
310  ShapeOpacity = 93,
311  ShapeBlendMode = 64,
312  ShapeFillColor = 58,
313  ShapeStrokeColor = 59,
314  ShapeStrokeWidth = 60,
315  ShapeStrokeWidthUnits = 61,
316  ShapeJoinStyle = 62,
317 
318  // drop shadow
319  ShadowDraw = 65,
320  ShadowUnder = 66,
321  ShadowOffsetAngle = 67,
322  ShadowOffsetDist = 68,
323  ShadowOffsetUnits = 69,
324  ShadowRadius = 70,
325  ShadowRadiusUnits = 71,
326  ShadowTransparency = 72,
327  ShadowOpacity = 95,
328  ShadowScale = 73,
329  ShadowColor = 74,
330  ShadowBlendMode = 75,
331 
332  // placement
333  CentroidWhole = 76,
334  OffsetQuad = 77,
335  OffsetXY = 78,
336  OffsetUnits = 80,
337  LabelDistance = 13,
338  DistanceUnits = 81,
339  OffsetRotation = 82,
340  CurvedCharAngleInOut = 83,
341  // (data defined only)
342  PositionX = 9,
343  PositionY = 10,
344  Hali = 11,
345  Vali = 12,
346  Rotation = 14,
347  LabelRotation = 96,
348  RepeatDistance = 84,
349  RepeatDistanceUnit = 86,
350  Priority = 87,
351  PredefinedPositionOrder = 91,
352 
353  // rendering
354  ScaleVisibility = 23,
355  MinScale = 16,
356  MinimumScale = 97,
357  MaxScale = 17,
358  MaximumScale = 98,
359  FontLimitPixel = 24,
360  FontMinPixel = 25,
361  FontMaxPixel = 26,
362  IsObstacle = 88,
363  ObstacleFactor = 89,
364  ZIndex = 90,
365 
366  // (data defined only)
367  Show = 15,
368  AlwaysShow = 20
369  };
370 
375  static const QgsPropertiesDefinition &propertyDefinitions();
376 
385 
386  //-- text style
387 
393  QString fieldName;
394 
400 
404  QgsExpression *getLabelExpression();
405 
407 
412 
413  //-- text formatting
414 
419  QString wrapChar;
420 
423 
435 
442 
449 
455 
458 
466 
472  int decimals;
473 
479  bool plusSign;
480 
481  //-- placement
482 
484  unsigned int placementFlags;
485 
491 
498 
505  QVector< PredefinedPointPosition > predefinedPositionOrder SIP_SKIP;
506 
511 
517  double dist;
518 
525 
532 
535 
542 
549 
556 
561 
568  double xOffset;
569 
576  double yOffset;
577 
585 
593 
595  double angleOffset;
596 
599 
605 
611 
616  int priority;
617 
618  //-- rendering
619 
626 
637  double maximumScale;
638 
649  double minimumScale;
650 
657 
664 
671 
674 
677 
683 
689 
695 
702 
707 
713  bool obstacle;
714 
722 
729 
731  double zIndex;
732 
733  // called from register feature hook
734  void calculateLabelSize( const QFontMetricsF *fm, QString text, double &labelX, double &labelY, QgsFeature *f = nullptr, QgsRenderContext *context = nullptr );
735 
748  void registerFeature( QgsFeature &f, QgsRenderContext &context,
749  QgsLabelFeature **labelFeature SIP_PYARGREMOVE = nullptr,
750  QgsGeometry obstacleGeometry SIP_PYARGREMOVE = QgsGeometry() );
751 
755  void readXml( QDomElement &elem, const QgsReadWriteContext &context );
756 
760  QDomElement writeXml( QDomDocument &doc, const QgsReadWriteContext &context );
761 
766  QgsPropertyCollection &dataDefinedProperties() { return mDataDefinedProperties; }
767 
773  const QgsPropertyCollection &dataDefinedProperties() const SIP_SKIP { return mDataDefinedProperties; }
774 
780  void setDataDefinedProperties( const QgsPropertyCollection &collection ) { mDataDefinedProperties = collection; }
781 
786  const QgsTextFormat &format() const { return mFormat; }
787 
793  void setFormat( const QgsTextFormat &format ) { mFormat = format; }
794 
795  // temporary stuff: set when layer gets prepared or labeled
796  QgsFeature *mCurFeat = nullptr;
799  const QgsMapToPixel *xform = nullptr;
801 
805  int mFeaturesToLabel; // total features that will probably be labeled, may be less (figured before PAL)
806  int mFeatsSendingToPal; // total features tested for sending into PAL (relative to maxNumLabels)
807  int mFeatsRegPal; // number of features registered in PAL, when using limitNumLabels
808 
809  private:
810 
811  friend class QgsVectorLayer; // to allow calling readFromLayerCustomProperties()
812 
816  void readFromLayerCustomProperties( QgsVectorLayer *layer );
817 
821  void readOldDataDefinedPropertyMap( QgsVectorLayer *layer, QDomElement *parentElem );
822 
826  void readOldDataDefinedProperty( QgsVectorLayer *layer, QgsPalLayerSettings::Property p );
827 
828  enum DataDefinedValueType
829  {
830  DDBool,
831  DDInt,
832  DDIntPos,
833  DDDouble,
834  DDDoublePos,
835  DDRotation180,
836  DDOpacity,
837  DDString,
838  DDUnits,
839  DDColor,
840  DDJoinStyle,
841  DDBlendMode,
842  DDPointF
843  };
844 
845  // convenience data defined evaluation function
846  bool dataDefinedValEval( DataDefinedValueType valType,
848  QVariant &exprVal, QgsExpressionContext &context, const QVariant &originalValue = QVariant() );
849 
850  void parseTextStyle( QFont &labelFont,
851  QgsUnitTypes::RenderUnit fontunits,
852  QgsRenderContext &context );
853 
854  void parseTextBuffer( QgsRenderContext &context );
855 
856  void parseTextFormatting( QgsRenderContext &context );
857 
858  void parseShapeBackground( QgsRenderContext &context );
859 
860  void parseDropShadow( QgsRenderContext &context );
861 
864  bool checkMinimumSizeMM( const QgsRenderContext &ct, const QgsGeometry &geom, double minSize ) const;
865 
868  void registerObstacleFeature( QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **obstacleFeature, const QgsGeometry &obstacleGeometry = QgsGeometry() );
869 
870  QMap<Property, QVariant> dataDefinedValues;
871 
873  QgsPropertyCollection mDataDefinedProperties;
874 
875  QgsExpression *expression = nullptr;
876 
877  QFontDatabase mFontDB;
878 
879  QgsTextFormat mFormat;
880 
881  static const QVector< PredefinedPointPosition > DEFAULT_PLACEMENT_ORDER;
882 
883  static void initPropertyDefinitions();
884 
886  static QgsPropertiesDefinition sPropertyDefinitions;
887 
888 };
889 
892 class CORE_EXPORT QgsLabelCandidate
893 {
894  public:
895  QgsLabelCandidate( const QRectF &r, double c ): rect( r ), cost( c ) {}
896 
897  QRectF rect;
898  double cost;
899 };
900 
901 
902 
903 
908 class CORE_EXPORT QgsLabelingResults
909 {
910  public:
913 
915  QgsLabelingResults( const QgsLabelingResults & ) = delete;
917  QgsLabelingResults &operator=( const QgsLabelingResults &rh ) = delete;
918 
920  QList<QgsLabelPosition> labelsAtPosition( const QgsPointXY &p ) const;
922  QList<QgsLabelPosition> labelsWithinRect( const QgsRectangle &r ) const;
923 
924  private:
925 #ifdef SIP_RUN
927 #endif
928 
929  QgsLabelSearchTree *mLabelSearchTree = nullptr;
930 
931  friend class QgsPalLabeling;
934 };
935 
939 class CORE_EXPORT QgsPalLabeling
940 {
941  public:
942 
945  static bool staticWillUseLayer( QgsVectorLayer *layer );
946 
948  static void drawLabelCandidateRect( pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList<QgsLabelCandidate> *candidates = nullptr ) SIP_SKIP;
949 
958  static QgsGeometry prepareGeometry( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry = QgsGeometry() ) SIP_FACTORY;
959 
968  static bool geometryRequiresPreparation( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry = QgsGeometry() );
969 
977  static QStringList splitToLines( const QString &text, const QString &wrapCharacter );
978 
986  static QStringList splitToGraphemes( const QString &text );
987 
988  private:
990  static void dataDefinedTextStyle( QgsPalLayerSettings &tmpLyr,
991  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
992 
994  static void dataDefinedTextFormatting( QgsPalLayerSettings &tmpLyr,
995  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
996 
998  static void dataDefinedTextBuffer( QgsPalLayerSettings &tmpLyr,
999  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1000 
1002  static void dataDefinedShapeBackground( QgsPalLayerSettings &tmpLyr,
1003  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1004 
1006  static void dataDefinedDropShadow( QgsPalLayerSettings &tmpLyr,
1007  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1008 
1009  friend class QgsVectorLayerLabelProvider; // to allow calling the static methods above
1010  friend class QgsDxfExport; // to allow calling the static methods above
1011 
1019  static bool checkMinimumSizeMM( const QgsRenderContext &context, const QgsGeometry &geom, double minSize );
1020 
1021  friend class QgsPalLayerSettings;
1022 };
1023 
1024 #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:38
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) ...
UpsideDownLabels upsidedownLabels
Controls whether upside down labels are displayed and how they are handled.
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:42
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:41
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:96
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:61
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:35
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:95
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...