QGIS API Documentation  3.2.0-Bonn (bc43194)
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  {}
98 
100  QgsLabelPosition() = default;
101 
102  int featureId = -1;
103  double rotation = 0;
104  QVector< QgsPointXY > cornerPoints;
106  double width = 0;
107  double height = 0;
108  QString layerID;
109  QString labelText;
110  QFont labelFont;
111  bool upsideDown = false;
112  bool isDiagram = false;
113  bool isPinned = false;
115  QString providerID;
116 };
117 
118 
123 class CORE_EXPORT QgsPalLayerSettings
124 {
125  public:
129 
131  QgsPalLayerSettings &operator=( const QgsPalLayerSettings &s );
132 
136  //TODO QGIS 3.0 - move to QgsLabelingEngine
138  {
147  };
148 
150  //TODO QGIS 3.0 - move to QgsLabelingEngine
152  {
165  };
166 
171  //TODO QGIS 3.0 - move to QgsLabelingEngine
173  {
176  };
177 
181  //TODO QGIS 3.0 - move to QgsLabelingEngine, rename to LinePlacementFlag, use Q_DECLARE_FLAGS to make
182  //LinePlacementFlags type, and replace use of pal::LineArrangementFlag
184  {
185  OnLine = 1,
186  AboveLine = 2,
189  BelowLine = 4,
192  MapOrientation = 8,
195  };
196 
198  {
208  };
209 
211  {
214  ShowAll
215  };
216 
218  {
221  SymbolBelow
222  };
223 
225  {
226  MultiLeft = 0,
229  MultiFollowPlacement
231  };
232 
237  //TODO QGIS 3.0 - Move to QgsLabelingEngine
239  {
240  PolygonInterior,
242  PolygonBoundary,
244  PolygonWhole
248  };
249 
251  enum Property
252  {
253  // text style
254  Size = 0,
255  Bold = 1,
256  Italic = 2,
257  Underline = 3,
258  Color = 4,
259  Strikeout = 5,
260  Family = 6,
261  FontStyle = 21,
262  FontSizeUnit = 22,
263  FontTransp = 18,
264  FontOpacity = 92,
265  FontCase = 27,
266  FontLetterSpacing = 28,
267  FontWordSpacing = 29,
268  FontBlendMode = 30,
269 
270  // text formatting
271  MultiLineWrapChar = 31,
272  MultiLineHeight = 32,
273  MultiLineAlignment = 33,
274  DirSymbDraw = 34,
275  DirSymbLeft = 35,
276  DirSymbRight = 36,
277  DirSymbPlacement = 37,
278  DirSymbReverse = 38,
279  NumFormat = 39,
280  NumDecimals = 40,
281  NumPlusSign = 41,
282 
283  // text buffer
284  BufferDraw = 42,
285  BufferSize = 7,
286  BufferUnit = 43,
287  BufferColor = 8,
288  BufferTransp = 19,
289  BufferOpacity = 94,
290  BufferJoinStyle = 44,
291  BufferBlendMode = 45,
292 
293  // background
294  ShapeDraw = 46,
295  ShapeKind = 47,
296  ShapeSVGFile = 48,
297  ShapeSizeType = 49,
298  ShapeSizeX = 50,
299  ShapeSizeY = 85,
300  ShapeSizeUnits = 51,
301  ShapeRotationType = 52,
302  ShapeRotation = 53,
303  ShapeOffset = 54,
304  ShapeOffsetUnits = 55,
305  ShapeRadii = 56,
306  ShapeRadiiUnits = 57,
307  ShapeTransparency = 63,
308  ShapeOpacity = 93,
309  ShapeBlendMode = 64,
310  ShapeFillColor = 58,
311  ShapeStrokeColor = 59,
312  ShapeStrokeWidth = 60,
313  ShapeStrokeWidthUnits = 61,
314  ShapeJoinStyle = 62,
315 
316  // drop shadow
317  ShadowDraw = 65,
318  ShadowUnder = 66,
319  ShadowOffsetAngle = 67,
320  ShadowOffsetDist = 68,
321  ShadowOffsetUnits = 69,
322  ShadowRadius = 70,
323  ShadowRadiusUnits = 71,
324  ShadowTransparency = 72,
325  ShadowOpacity = 95,
326  ShadowScale = 73,
327  ShadowColor = 74,
328  ShadowBlendMode = 75,
329 
330  // placement
331  CentroidWhole = 76,
332  OffsetQuad = 77,
333  OffsetXY = 78,
334  OffsetUnits = 80,
335  LabelDistance = 13,
336  DistanceUnits = 81,
337  OffsetRotation = 82,
338  CurvedCharAngleInOut = 83,
339  // (data defined only)
340  PositionX = 9,
341  PositionY = 10,
342  Hali = 11,
343  Vali = 12,
344  Rotation = 14,
345  LabelRotation = 96,
346  RepeatDistance = 84,
347  RepeatDistanceUnit = 86,
348  Priority = 87,
349  PredefinedPositionOrder = 91,
350 
351  // rendering
352  ScaleVisibility = 23,
353  MinScale = 16,
354  MinimumScale = 97,
355  MaxScale = 17,
356  MaximumScale = 98,
357  FontLimitPixel = 24,
358  FontMinPixel = 25,
359  FontMaxPixel = 26,
360  IsObstacle = 88,
361  ObstacleFactor = 89,
362  ZIndex = 90,
363 
364  // (data defined only)
365  Show = 15,
366  AlwaysShow = 20
367  };
368 
373  static const QgsPropertiesDefinition &propertyDefinitions();
374 
384 
385  //-- text style
386 
392  QString fieldName;
393 
399 
403  QgsExpression *getLabelExpression();
404 
406 
411 
412  //-- text formatting
413 
418  QString wrapChar;
419 
422 
434 
441 
448 
454 
457 
465 
471  int decimals;
472 
478  bool plusSign;
479 
480  //-- placement
481 
483  unsigned int placementFlags;
484 
490 
497 
504  QVector< PredefinedPointPosition > predefinedPositionOrder SIP_SKIP;
505 
510 
516  double dist;
517 
524 
531 
534 
541 
548 
555 
560 
567  double xOffset;
568 
575  double yOffset;
576 
584 
592 
594  double angleOffset;
595 
598 
604 
610 
615  int priority;
616 
617  //-- rendering
618 
625 
636  double maximumScale;
637 
648  double minimumScale;
649 
656 
663 
670 
673 
675  UpsideDownLabels upsidedownLabels = Upright;
676 
682 
688 
694 
701 
706 
712  bool obstacle;
713 
721 
728 
730  double zIndex;
731 
732  // called from register feature hook
733  void calculateLabelSize( const QFontMetricsF *fm, QString text, double &labelX, double &labelY, QgsFeature *f = nullptr, QgsRenderContext *context = nullptr );
734 
748  void registerFeature( QgsFeature &f, QgsRenderContext &context,
749  QgsLabelFeature **labelFeature SIP_PYARGREMOVE = nullptr,
750  QgsGeometry obstacleGeometry SIP_PYARGREMOVE = QgsGeometry() );
751 
756  void readXml( QDomElement &elem, const QgsReadWriteContext &context );
757 
762  QDomElement writeXml( QDomDocument &doc, const QgsReadWriteContext &context );
763 
769  QgsPropertyCollection &dataDefinedProperties() { return mDataDefinedProperties; }
770 
777  const QgsPropertyCollection &dataDefinedProperties() const SIP_SKIP { return mDataDefinedProperties; }
778 
785  void setDataDefinedProperties( const QgsPropertyCollection &collection ) { mDataDefinedProperties = collection; }
786 
792  const QgsTextFormat &format() const { return mFormat; }
793 
800  void setFormat( const QgsTextFormat &format ) { mFormat = format; }
801 
802  // temporary stuff: set when layer gets prepared or labeled
803  QgsFeature *mCurFeat = nullptr;
806  const QgsMapToPixel *xform = nullptr;
808 
812  int mFeaturesToLabel = 0; // total features that will probably be labeled, may be less (figured before PAL)
813  int mFeatsSendingToPal = 0; // total features tested for sending into PAL (relative to maxNumLabels)
814  int mFeatsRegPal = 0; // number of features registered in PAL, when using limitNumLabels
815 
816  private:
817 
818  friend class QgsVectorLayer; // to allow calling readFromLayerCustomProperties()
819 
824  void readFromLayerCustomProperties( QgsVectorLayer *layer );
825 
829  void readOldDataDefinedPropertyMap( QgsVectorLayer *layer, QDomElement *parentElem );
830 
834  void readOldDataDefinedProperty( QgsVectorLayer *layer, QgsPalLayerSettings::Property p );
835 
836  enum DataDefinedValueType
837  {
838  DDBool,
839  DDInt,
840  DDIntPos,
841  DDDouble,
842  DDDoublePos,
843  DDRotation180,
844  DDOpacity,
845  DDString,
846  DDUnits,
847  DDColor,
848  DDJoinStyle,
849  DDBlendMode,
850  DDPointF,
851  DDSizeF,
852  };
853 
854  // convenience data defined evaluation function
855  bool dataDefinedValEval( DataDefinedValueType valType,
857  QVariant &exprVal, QgsExpressionContext &context, const QVariant &originalValue = QVariant() );
858 
859  void parseTextStyle( QFont &labelFont,
860  QgsUnitTypes::RenderUnit fontunits,
861  QgsRenderContext &context );
862 
863  void parseTextBuffer( QgsRenderContext &context );
864 
865  void parseTextFormatting( QgsRenderContext &context );
866 
867  void parseShapeBackground( QgsRenderContext &context );
868 
869  void parseDropShadow( QgsRenderContext &context );
870 
874  bool checkMinimumSizeMM( const QgsRenderContext &ct, const QgsGeometry &geom, double minSize ) const;
875 
879  void registerObstacleFeature( QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **obstacleFeature, const QgsGeometry &obstacleGeometry = QgsGeometry() );
880 
881  QMap<Property, QVariant> dataDefinedValues;
882 
884  QgsPropertyCollection mDataDefinedProperties;
885 
886  QgsExpression *expression = nullptr;
887 
888  QFontDatabase mFontDB;
889 
890  QgsTextFormat mFormat;
891 
892  static const QVector< PredefinedPointPosition > DEFAULT_PLACEMENT_ORDER;
893 
894  static void initPropertyDefinitions();
895 
897  static QgsPropertiesDefinition sPropertyDefinitions;
898 
899 };
900 
904 class CORE_EXPORT QgsLabelCandidate
905 {
906  public:
907  QgsLabelCandidate( const QRectF &r, double c ): rect( r ), cost( c ) {}
908 
909  QRectF rect;
910  double cost;
911 };
912 
913 
914 
915 
921 class CORE_EXPORT QgsLabelingResults
922 {
923  public:
926 
928  QgsLabelingResults( const QgsLabelingResults & ) = delete;
930  QgsLabelingResults &operator=( const QgsLabelingResults &rh ) = delete;
931 
933  QList<QgsLabelPosition> labelsAtPosition( const QgsPointXY &p ) const;
935  QList<QgsLabelPosition> labelsWithinRect( const QgsRectangle &r ) const;
936 
937  private:
938 #ifdef SIP_RUN
940 #endif
941 
942  QgsLabelSearchTree *mLabelSearchTree = nullptr;
943 
944  friend class QgsPalLabeling;
947 };
948 
953 class CORE_EXPORT QgsPalLabeling
954 {
955  public:
956 
961  static bool staticWillUseLayer( QgsVectorLayer *layer );
962 
964  static void drawLabelCandidateRect( pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList<QgsLabelCandidate> *candidates = nullptr ) SIP_SKIP;
965 
975  static QgsGeometry prepareGeometry( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry = QgsGeometry() ) SIP_FACTORY;
976 
986  static bool geometryRequiresPreparation( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry = QgsGeometry() );
987 
996  static QStringList splitToLines( const QString &text, const QString &wrapCharacter );
997 
1006  static QStringList splitToGraphemes( const QString &text );
1007 
1008  private:
1010  static void dataDefinedTextStyle( QgsPalLayerSettings &tmpLyr,
1011  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1012 
1014  static void dataDefinedTextFormatting( QgsPalLayerSettings &tmpLyr,
1015  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1016 
1018  static void dataDefinedTextBuffer( QgsPalLayerSettings &tmpLyr,
1019  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1020 
1022  static void dataDefinedShapeBackground( QgsPalLayerSettings &tmpLyr,
1023  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1024 
1026  static void dataDefinedDropShadow( QgsPalLayerSettings &tmpLyr,
1027  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
1028 
1029  friend class QgsVectorLayerLabelProvider; // to allow calling the static methods above
1030  friend class QgsDxfExport; // to allow calling the static methods above
1031 
1040  static bool checkMinimumSizeMM( const QgsRenderContext &context, const QgsGeometry &geom, double minSize );
1041 
1042  friend class QgsPalLayerSettings;
1043 };
1044 
1045 #endif // QGSPALLABELING_H
Label below point, slightly right of center.
QgsRectangle labelRect
Class for parsing and evaluation of expressions (formerly called "search strings").
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:40
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 wrapper 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:104
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.
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
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...