QGIS API Documentation  2.99.0-Master (23ddace)
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 
252 
254  enum SizeUnit
255  {
256  Points = 0,
257  MM,
259  Percent
260  };
261 
263  enum Property
264  {
265  // text style
266  Size = 0,
267  Bold = 1,
268  Italic = 2,
269  Underline = 3,
270  Color = 4,
271  Strikeout = 5,
272  Family = 6,
273  FontStyle = 21,
274  FontSizeUnit = 22,
275  FontTransp = 18,
276  FontOpacity = 92,
277  FontCase = 27,
278  FontLetterSpacing = 28,
279  FontWordSpacing = 29,
280  FontBlendMode = 30,
281 
282  // text formatting
283  MultiLineWrapChar = 31,
284  MultiLineHeight = 32,
285  MultiLineAlignment = 33,
286  DirSymbDraw = 34,
287  DirSymbLeft = 35,
288  DirSymbRight = 36,
289  DirSymbPlacement = 37,
290  DirSymbReverse = 38,
291  NumFormat = 39,
292  NumDecimals = 40,
293  NumPlusSign = 41,
294 
295  // text buffer
296  BufferDraw = 42,
297  BufferSize = 7,
298  BufferUnit = 43,
299  BufferColor = 8,
300  BufferTransp = 19,
301  BufferOpacity = 94,
302  BufferJoinStyle = 44,
303  BufferBlendMode = 45,
304 
305  // background
306  ShapeDraw = 46,
307  ShapeKind = 47,
308  ShapeSVGFile = 48,
309  ShapeSizeType = 49,
310  ShapeSizeX = 50,
311  ShapeSizeY = 85,
312  ShapeSizeUnits = 51,
313  ShapeRotationType = 52,
314  ShapeRotation = 53,
315  ShapeOffset = 54,
316  ShapeOffsetUnits = 55,
317  ShapeRadii = 56,
318  ShapeRadiiUnits = 57,
319  ShapeTransparency = 63,
320  ShapeOpacity = 93,
321  ShapeBlendMode = 64,
322  ShapeFillColor = 58,
323  ShapeStrokeColor = 59,
324  ShapeStrokeWidth = 60,
325  ShapeStrokeWidthUnits = 61,
326  ShapeJoinStyle = 62,
327 
328  // drop shadow
329  ShadowDraw = 65,
330  ShadowUnder = 66,
331  ShadowOffsetAngle = 67,
332  ShadowOffsetDist = 68,
333  ShadowOffsetUnits = 69,
334  ShadowRadius = 70,
335  ShadowRadiusUnits = 71,
336  ShadowTransparency = 72,
337  ShadowOpacity = 95,
338  ShadowScale = 73,
339  ShadowColor = 74,
340  ShadowBlendMode = 75,
341 
342  // placement
343  CentroidWhole = 76,
344  OffsetQuad = 77,
345  OffsetXY = 78,
346  OffsetUnits = 80,
347  LabelDistance = 13,
348  DistanceUnits = 81,
349  OffsetRotation = 82,
350  CurvedCharAngleInOut = 83,
351  // (data defined only)
352  PositionX = 9,
353  PositionY = 10,
354  Hali = 11,
355  Vali = 12,
356  Rotation = 14,
357  LabelRotation = 96,
358  RepeatDistance = 84,
359  RepeatDistanceUnit = 86,
360  Priority = 87,
361  PredefinedPositionOrder = 91,
362 
363  // rendering
364  ScaleVisibility = 23,
365  MinScale = 16,
366  MinimumScale = 97,
367  MaxScale = 17,
368  MaximumScale = 98,
369  FontLimitPixel = 24,
370  FontMinPixel = 25,
371  FontMaxPixel = 26,
372  IsObstacle = 88,
373  ObstacleFactor = 89,
374  ZIndex = 90,
375 
376  // (data defined only)
377  Show = 15,
378  AlwaysShow = 20
379  };
380 
385  static const QgsPropertiesDefinition &propertyDefinitions();
386 
395 
396  //-- text style
397 
398  QString fieldName;
399 
403 
406  QgsExpression *getLabelExpression();
407 
409 
414 
415  //-- text formatting
416 
417  QString wrapChar;
418  MultiLineAlign multilineAlign; // horizontal alignment of multi-line labels
419 
420  // Adds '<' or '>', or user-defined symbol to the label string pointing to the
421  // direction of the line / polygon ring
422  // Works only if Placement == Line
426  DirectionSymbols placeDirectionSymbol; // whether to place left/right, above or below label
428 
430  int decimals;
431  bool plusSign;
432 
433  //-- placement
434 
436  unsigned int placementFlags;
437 
438  bool centroidWhole; // whether centroid calculated from whole or visible polygon
439  bool centroidInside; // whether centroid-point calculated must be inside polygon
440 
446  QVector< PredefinedPointPosition > predefinedPositionOrder SIP_SKIP;
447 
451  double dist; // distance from the feature (in mm)
452  bool distInMapUnits; //true if distance is in map units (otherwise in mm)
456 
460 
461  // offset labels of point/centroid features default to center
462  // move label to quadrant: left/down, don't move, right/up (-1, 0, 1)
464 
465  double xOffset; // offset from point in mm or map units
466  double yOffset; // offset from point in mm or map units
467  bool labelOffsetInMapUnits; //true if label offset is in map units (otherwise in mm)
469 
471  double angleOffset;
472 
473  bool preserveRotation; // preserve predefined rotation data during label pin/unpin operations
474 
475  double maxCurvedCharAngleIn; // maximum angle between inside curved label characters (defaults to 20.0, range 20.0 to 60.0)
476  double maxCurvedCharAngleOut; // maximum angle between outside curved label characters (defaults to -20.0, range -20.0 to -95.0)
477 
478  int priority; // 0 = low, 10 = high
479 
480  //-- rendering
481 
483 
490  double maximumScale;
491 
498  double minimumScale;
499 
500  bool fontLimitPixelSize; // true is label should be limited by fontMinPixelSize/fontMaxPixelSize
501  int fontMinPixelSize; // minimum pixel size for showing rendered map unit labels (1 - 1000)
502  int fontMaxPixelSize; // maximum pixel size for showing rendered map unit labels (1 - 10000)
503 
504  bool displayAll; // if true, all features will be labelled even though overlaps occur
505  UpsideDownLabels upsidedownLabels; // whether, or how, to show upsidedown labels
506 
507  bool labelPerPart; // whether to label every feature's part or only the biggest one
509 
510  bool limitNumLabels; // whether to limit the number of labels to be drawn
511  int maxNumLabels; // maximum number of labels to be drawn
512 
513  double minFeatureSize; // minimum feature size to be labelled (in mm)
514  bool obstacle; // whether features for layer are obstacles to labels of other layers
515 
520 
524 
526  double zIndex;
527 
528  // called from register feature hook
529  void calculateLabelSize( const QFontMetricsF *fm, QString text, double &labelX, double &labelY, QgsFeature *f = nullptr, QgsRenderContext *context = nullptr );
530 
543  void registerFeature( QgsFeature &f, QgsRenderContext &context,
544  QgsLabelFeature **labelFeature SIP_PYARGREMOVE = nullptr,
545  QgsGeometry obstacleGeometry SIP_PYARGREMOVE = QgsGeometry() );
546 
550  void readXml( QDomElement &elem, const QgsReadWriteContext &context );
551 
555  QDomElement writeXml( QDomDocument &doc, const QgsReadWriteContext &context );
556 
561  QgsPropertyCollection &dataDefinedProperties() { return mDataDefinedProperties; }
562 
568  const QgsPropertyCollection &dataDefinedProperties() const SIP_SKIP { return mDataDefinedProperties; }
569 
575  void setDataDefinedProperties( const QgsPropertyCollection &collection ) { mDataDefinedProperties = collection; }
576 
581  const QgsTextFormat &format() const { return mFormat; }
582 
588  void setFormat( const QgsTextFormat &format ) { mFormat = format; }
589 
590  // temporary stuff: set when layer gets prepared or labeled
591  QgsFeature *mCurFeat = nullptr;
594  const QgsMapToPixel *xform = nullptr;
596 
600  int mFeaturesToLabel; // total features that will probably be labeled, may be less (figured before PAL)
601  int mFeatsSendingToPal; // total features tested for sending into PAL (relative to maxNumLabels)
602  int mFeatsRegPal; // number of features registered in PAL, when using limitNumLabels
603 
604  private:
605 
606  friend class QgsVectorLayer; // to allow calling readFromLayerCustomProperties()
607 
611  void readFromLayerCustomProperties( QgsVectorLayer *layer );
612 
616  void readOldDataDefinedPropertyMap( QgsVectorLayer *layer, QDomElement *parentElem );
617 
621  void readOldDataDefinedProperty( QgsVectorLayer *layer, QgsPalLayerSettings::Property p );
622 
623  enum DataDefinedValueType
624  {
625  DDBool,
626  DDInt,
627  DDIntPos,
628  DDDouble,
629  DDDoublePos,
630  DDRotation180,
631  DDOpacity,
632  DDString,
633  DDUnits,
634  DDColor,
635  DDJoinStyle,
636  DDBlendMode,
637  DDPointF
638  };
639 
640  // convenience data defined evaluation function
641  bool dataDefinedValEval( DataDefinedValueType valType,
643  QVariant &exprVal, QgsExpressionContext &context, const QVariant &originalValue = QVariant() );
644 
645  void parseTextStyle( QFont &labelFont,
646  QgsUnitTypes::RenderUnit fontunits,
647  QgsRenderContext &context );
648 
649  void parseTextBuffer( QgsRenderContext &context );
650 
651  void parseTextFormatting( QgsRenderContext &context );
652 
653  void parseShapeBackground( QgsRenderContext &context );
654 
655  void parseDropShadow( QgsRenderContext &context );
656 
659  bool checkMinimumSizeMM( const QgsRenderContext &ct, const QgsGeometry &geom, double minSize ) const;
660 
663  void registerObstacleFeature( QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **obstacleFeature, const QgsGeometry &obstacleGeometry = QgsGeometry() );
664 
665  QMap<Property, QVariant> dataDefinedValues;
666 
668  QgsPropertyCollection mDataDefinedProperties;
669 
670  QgsExpression *expression = nullptr;
671 
672  QFontDatabase mFontDB;
673 
674  QgsTextFormat mFormat;
675 
676  static const QVector< PredefinedPointPosition > DEFAULT_PLACEMENT_ORDER;
677 
678  static void initPropertyDefinitions();
679 
681  static QgsPropertiesDefinition sPropertyDefinitions;
682 
683 };
684 
687 class CORE_EXPORT QgsLabelCandidate
688 {
689  public:
690  QgsLabelCandidate( const QRectF &r, double c ): rect( r ), cost( c ) {}
691 
692  QRectF rect;
693  double cost;
694 };
695 
696 
697 
698 
703 class CORE_EXPORT QgsLabelingResults
704 {
705  public:
708 
710  QgsLabelingResults( const QgsLabelingResults & ) = delete;
712  QgsLabelingResults &operator=( const QgsLabelingResults &rh ) = delete;
713 
715  QList<QgsLabelPosition> labelsAtPosition( const QgsPointXY &p ) const;
717  QList<QgsLabelPosition> labelsWithinRect( const QgsRectangle &r ) const;
718 
719  private:
720 #ifdef SIP_RUN
722 #endif
723 
724  QgsLabelSearchTree *mLabelSearchTree = nullptr;
725 
726  friend class QgsPalLabeling;
729 };
730 
734 class CORE_EXPORT QgsPalLabeling
735 {
736  public:
737 
740  static bool staticWillUseLayer( QgsVectorLayer *layer );
741 
743  static void drawLabelCandidateRect( pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList<QgsLabelCandidate> *candidates = nullptr ) SIP_SKIP;
744 
753  static QgsGeometry prepareGeometry( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry = QgsGeometry() ) SIP_FACTORY;
754 
763  static bool geometryRequiresPreparation( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry = QgsGeometry() );
764 
772  static QStringList splitToLines( const QString &text, const QString &wrapCharacter );
773 
781  static QStringList splitToGraphemes( const QString &text );
782 
783  private:
785  static void dataDefinedTextStyle( QgsPalLayerSettings &tmpLyr,
786  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
787 
789  static void dataDefinedTextFormatting( QgsPalLayerSettings &tmpLyr,
790  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
791 
793  static void dataDefinedTextBuffer( QgsPalLayerSettings &tmpLyr,
794  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
795 
797  static void dataDefinedShapeBackground( QgsPalLayerSettings &tmpLyr,
798  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
799 
801  static void dataDefinedDropShadow( QgsPalLayerSettings &tmpLyr,
802  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
803 
804  friend class QgsVectorLayerLabelProvider; // to allow calling the static methods above
805  friend class QgsDxfExport; // to allow calling the static methods above
806 
814  static bool checkMinimumSizeMM( const QgsRenderContext &context, const QgsGeometry &geom, double minSize );
815 
816  friend class QgsPalLayerSettings;
817 };
818 
819 #endif // QGSPALLABELING_H
Label below point, slightly right of center.
QgsRectangle labelRect
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 maximumScale
The maximum map scale (i.e.
double angleOffset
Label rotation, in degrees clockwise.
A class to query the labeling structure at a given point (small wraper around pal RTree class) ...
UpsideDownLabels upsidedownLabels
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
Candidates are placed in predefined positions around a point. Preference is given to positions with g...
QuadrantPosition quadOffset
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.
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.
QgsMapUnitScale repeatDistanceMapUnitScale
MultiLineAlign multilineAlign
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:61
QgsCoordinateTransform ct
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.
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.
#define SIP_SKIP
Definition: qgis_sip.h:107
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:57
SizeUnit
Units used for option sizes, before being converted to rendered sizes.
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.
Place direction symbols on above label.
Stores the settings for rendering of all diagrams for a layer.
unsigned int placementFlags
Placement
Placement modes which determine how label candidates are generated for a feature. ...
#define SIP_PYARGREMOVE
Definition: qgis_sip.h:127
The QgsLabelingEngine class provides map labeling functionality.
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.
The QgsLabelFeature class describes a feature that should be used within the labeling engine...
QgsGeometry extentGeom
QgsMapUnitScale distMapUnitScale
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)
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:52
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 isExpression
Is this label 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.
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.
QgsMapUnitScale labelOffsetMapUnitScale
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.
ObstacleType
Valid obstacle types, which affect how features within the layer will act as obstacles for labels...
DirectionSymbols placeDirectionSymbol
Arranges candidates scattered throughout a polygon feature. Candidates are rotated to respect the pol...