QGIS API Documentation  2.99.0-Master (5169e0d)
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 <QString>
26 #include <QFont>
27 #include <QFontDatabase>
28 #include <QColor>
29 #include <QHash>
30 #include <QList>
31 #include <QPainter>
32 #include <QRectF>
33 #include <QMap>
34 #include "qgsfeature.h"
35 #include "qgsgeometry.h"
36 #include "qgsfields.h"
38 #include "qgspoint.h"
39 #include "qgsmapunitscale.h"
40 #include "qgsstringutils.h"
41 #include "qgstextrenderer.h"
42 #include "qgspropertycollection.h"
43 
44 namespace pal
45 {
46  class Pal;
47  class Layer;
48  class LabelPosition;
49 }
50 
52 class QgsRectangle;
53 class QgsMapToPixel;
54 class QgsFeature;
56 class QgsVectorLayer;
57 class QgsExpression;
58 class QFontMetricsF;
59 class QPainter;
60 class QPicture;
61 class QgsGeometry;
63 class QgsLabelSearchTree;
64 class QgsMapSettings;
65 class QgsLabelFeature;
66 class QgsLabelingEngine;
69 class QgsDxfExport;
72 
73 
77 class CORE_EXPORT QgsLabelPosition
78 {
79  public:
80  QgsLabelPosition( int id, double r, const QVector< QgsPoint > &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() )
81  : featureId( id )
82  , rotation( r )
83  , cornerPoints( corners )
84  , labelRect( rect )
85  , width( w )
86  , height( h )
87  , layerID( layer )
88  , labelText( labeltext )
89  , labelFont( labelfont )
90  , upsideDown( upside_down )
91  , isDiagram( diagram )
92  , isPinned( pinned )
93  , providerID( providerId )
94  {}
96  : featureId( -1 )
97  , rotation( 0 )
98  , labelRect( QgsRectangle() )
99  , width( 0 )
100  , height( 0 )
101  , layerID( QLatin1String( "" ) )
102  , labelText( QLatin1String( "" ) )
103  , labelFont( QFont() )
104  , upsideDown( false )
105  , isDiagram( false )
106  , isPinned( false )
107  {}
109  double rotation;
110  QVector< QgsPoint > cornerPoints;
112  double width;
113  double height;
114  QString layerID;
115  QString labelText;
116  QFont labelFont;
118  bool isDiagram;
119  bool isPinned;
121  QString providerID;
122 };
123 
124 
128 class CORE_EXPORT QgsPalLayerSettings
129 {
130  public:
134 
136  QgsPalLayerSettings &operator=( const QgsPalLayerSettings &s );
137 
139  static QgsPalLayerSettings fromLayer( QgsVectorLayer *layer );
140 
143  //TODO QGIS 3.0 - move to QgsLabelingEngine
145  {
154  };
155 
157  //TODO QGIS 3.0 - move to QgsLabelingEngine
159  {
172  };
173 
176  //TODO QGIS 3.0 - move to QgsLabelingEngine
178  {
181  };
182 
185  //TODO QGIS 3.0 - move to QgsLabelingEngine, rename to LinePlacementFlag, use Q_DECLARE_FLAGS to make
186  //LinePlacementFlags type, and replace use of pal::LineArrangementFlag
188  {
189  OnLine = 1,
190  AboveLine = 2,
193  BelowLine = 4,
196  MapOrientation = 8,
199  };
200 
202  {
211  QuadrantBelowRight
212  };
213 
215  {
218  ShowAll
219  };
220 
222  {
225  SymbolBelow
226  };
227 
229  {
230  MultiLeft = 0,
233  MultiFollowPlacement
235  };
236 
240  //TODO QGIS 3.0 - Move to QgsLabelingEngine
242  {
243  PolygonInterior,
245  PolygonBoundary,
247  PolygonWhole
251  };
252 
253 
255  enum SizeUnit
256  {
257  Points = 0,
258  MM,
260  Percent
261  };
262 
264  enum Property
265  {
266  // text style
267  Size = 0,
268  Bold = 1,
269  Italic = 2,
270  Underline = 3,
271  Color = 4,
272  Strikeout = 5,
273  Family = 6,
274  FontStyle = 21,
275  FontSizeUnit = 22,
276  FontTransp = 18,
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  BufferJoinStyle = 44,
302  BufferBlendMode = 45,
303 
304  // background
305  ShapeDraw = 46,
306  ShapeKind = 47,
307  ShapeSVGFile = 48,
308  ShapeSizeType = 49,
309  ShapeSizeX = 50,
310  ShapeSizeY = 85,
311  ShapeSizeUnits = 51,
312  ShapeRotationType = 52,
313  ShapeRotation = 53,
314  ShapeOffset = 54,
315  ShapeOffsetUnits = 55,
316  ShapeRadii = 56,
317  ShapeRadiiUnits = 57,
318  ShapeTransparency = 63,
319  ShapeBlendMode = 64,
320  ShapeFillColor = 58,
321  ShapeStrokeColor = 59,
322  ShapeStrokeWidth = 60,
323  ShapeStrokeWidthUnits = 61,
324  ShapeJoinStyle = 62,
325 
326  // drop shadow
327  ShadowDraw = 65,
328  ShadowUnder = 66,
329  ShadowOffsetAngle = 67,
330  ShadowOffsetDist = 68,
331  ShadowOffsetUnits = 69,
332  ShadowRadius = 70,
333  ShadowRadiusUnits = 71,
334  ShadowTransparency = 72,
335  ShadowScale = 73,
336  ShadowColor = 74,
337  ShadowBlendMode = 75,
338 
339  // placement
340  CentroidWhole = 76,
341  OffsetQuad = 77,
342  OffsetXY = 78,
343  OffsetUnits = 80,
344  LabelDistance = 13,
345  DistanceUnits = 81,
346  OffsetRotation = 82,
347  CurvedCharAngleInOut = 83,
348  // (data defined only)
349  PositionX = 9,
350  PositionY = 10,
351  Hali = 11,
352  Vali = 12,
353  Rotation = 14,
354  RepeatDistance = 84,
355  RepeatDistanceUnit = 86,
356  Priority = 87,
357  PredefinedPositionOrder = 91,
358 
359  // rendering
360  ScaleVisibility = 23,
361  MinScale = 16,
362  MaxScale = 17,
363  FontLimitPixel = 24,
364  FontMinPixel = 25,
365  FontMaxPixel = 26,
366  IsObstacle = 88,
367  ObstacleFactor = 89,
368  ZIndex = 90,
369 
370  // (data defined only)
371  Show = 15,
372  AlwaysShow = 20
373  };
374 
379  static const QgsPropertiesDefinition &propertyDefinitions();
380 
381 
382  // whether to label this layer
383  bool enabled;
384 
393 
394  //-- text style
395 
396  QString fieldName;
397 
401 
404  QgsExpression *getLabelExpression();
405 
407 
412 
413  //-- text formatting
414 
415  QString wrapChar;
416  MultiLineAlign multilineAlign; // horizontal alignment of multi-line labels
417 
418  // Adds '<' or '>', or user-defined symbol to the label string pointing to the
419  // direction of the line / polygon ring
420  // Works only if Placement == Line
424  DirectionSymbols placeDirectionSymbol; // whether to place left/right, above or below label
426 
428  int decimals;
429  bool plusSign;
430 
431  //-- placement
432 
434  unsigned int placementFlags;
435 
436  bool centroidWhole; // whether centroid calculated from whole or visible polygon
437  bool centroidInside; // whether centroid-point calculated must be inside polygon
438 
444  QVector< PredefinedPointPosition > predefinedPositionOrder;
445 
449  double dist; // distance from the feature (in mm)
450  bool distInMapUnits; //true if distance is in map units (otherwise in mm)
454 
458 
459  // offset labels of point/centroid features default to center
460  // move label to quadrant: left/down, don't move, right/up (-1, 0, 1)
462 
463  double xOffset; // offset from point in mm or map units
464  double yOffset; // offset from point in mm or map units
465  bool labelOffsetInMapUnits; //true if label offset is in map units (otherwise in mm)
467  double angleOffset; // rotation applied to offset labels
468  bool preserveRotation; // preserve predefined rotation data during label pin/unpin operations
469 
470  double maxCurvedCharAngleIn; // maximum angle between inside curved label characters (defaults to 20.0, range 20.0 to 60.0)
471  double maxCurvedCharAngleOut; // maximum angle between outside curved label characters (defaults to -20.0, range -20.0 to -95.0)
472 
473  int priority; // 0 = low, 10 = high
474 
475  //-- rendering
476 
478  int scaleMin;
479  int scaleMax;
480 
481  bool fontLimitPixelSize; // true is label should be limited by fontMinPixelSize/fontMaxPixelSize
482  int fontMinPixelSize; // minimum pixel size for showing rendered map unit labels (1 - 1000)
483  int fontMaxPixelSize; // maximum pixel size for showing rendered map unit labels (1 - 10000)
484 
485  bool displayAll; // if true, all features will be labelled even though overlaps occur
486  UpsideDownLabels upsidedownLabels; // whether, or how, to show upsidedown labels
487 
488  bool labelPerPart; // whether to label every feature's part or only the biggest one
490 
491  bool limitNumLabels; // whether to limit the number of labels to be drawn
492  int maxNumLabels; // maximum number of labels to be drawn
493 
494  double minFeatureSize; // minimum feature size to be labelled (in mm)
495  bool obstacle; // whether features for layer are obstacles to labels of other layers
496 
501 
505 
507  double zIndex;
508 
509  // called from register feature hook
510  void calculateLabelSize( const QFontMetricsF *fm, QString text, double &labelX, double &labelY, QgsFeature *f = nullptr, QgsRenderContext *context = nullptr );
511 
524  void registerFeature( QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **labelFeature = nullptr, QgsGeometry *obstacleGeometry = nullptr );
525 
526  void readFromLayer( QgsVectorLayer *layer );
527  void writeToLayer( QgsVectorLayer *layer );
528 
532  void readXml( QDomElement &elem );
533 
537  QDomElement writeXml( QDomDocument &doc );
538 
543  QgsPropertyCollection &dataDefinedProperties() { return mDataDefinedProperties; }
544 
549  const QgsPropertyCollection &dataDefinedProperties() const { return mDataDefinedProperties; }
550 
556  void setDataDefinedProperties( const QgsPropertyCollection &collection ) { mDataDefinedProperties = collection; }
557 
562  const QgsTextFormat &format() const { return mFormat; }
563 
569  void setFormat( const QgsTextFormat &format ) { mFormat = format; }
570 
571  // temporary stuff: set when layer gets prepared or labeled
572  QgsFeature *mCurFeat = nullptr;
575  const QgsMapToPixel *xform = nullptr;
577 
581  int mFeaturesToLabel; // total features that will probably be labeled, may be less (figured before PAL)
582  int mFeatsSendingToPal; // total features tested for sending into PAL (relative to maxNumLabels)
583  int mFeatsRegPal; // number of features registered in PAL, when using limitNumLabels
584 
585  private:
586 
590  void readOldDataDefinedPropertyMap( QgsVectorLayer *layer, QDomElement *parentElem );
591 
595  void readOldDataDefinedProperty( QgsVectorLayer *layer, QgsPalLayerSettings::Property p );
596 
597  enum DataDefinedValueType
598  {
599  DDBool,
600  DDInt,
601  DDIntPos,
602  DDDouble,
603  DDDoublePos,
604  DDRotation180,
605  DDTransparency,
606  DDString,
607  DDUnits,
608  DDColor,
609  DDJoinStyle,
610  DDBlendMode,
611  DDPointF
612  };
613 
614  // convenience data defined evaluation function
615  bool dataDefinedValEval( DataDefinedValueType valType,
617  QVariant &exprVal, QgsExpressionContext &context, const QVariant &originalValue = QVariant() );
618 
619  void parseTextStyle( QFont &labelFont,
620  QgsUnitTypes::RenderUnit fontunits,
621  QgsRenderContext &context );
622 
623  void parseTextBuffer( QgsRenderContext &context );
624 
625  void parseTextFormatting( QgsRenderContext &context );
626 
627  void parseShapeBackground( QgsRenderContext &context );
628 
629  void parseDropShadow( QgsRenderContext &context );
630 
633  bool checkMinimumSizeMM( const QgsRenderContext &ct, const QgsGeometry &geom, double minSize ) const;
634 
637  void registerObstacleFeature( QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **obstacleFeature, QgsGeometry *obstacleGeometry = nullptr );
638 
639  QMap<Property, QVariant> dataDefinedValues;
640 
642  QgsPropertyCollection mDataDefinedProperties;
643 
644  QgsExpression *expression = nullptr;
645 
646  QFontDatabase mFontDB;
647 
648  QgsTextFormat mFormat;
649 
650  static const QVector< PredefinedPointPosition > DEFAULT_PLACEMENT_ORDER;
651 
652  static void initPropertyDefinitions();
653 
655  static QgsPropertiesDefinition sPropertyDefinitions;
656 
657 };
658 
661 class CORE_EXPORT QgsLabelCandidate
662 {
663  public:
664  QgsLabelCandidate( const QRectF &r, double c ): rect( r ), cost( c ) {}
665 
666  QRectF rect;
667  double cost;
668 };
669 
670 
671 
672 
677 class CORE_EXPORT QgsLabelingResults
678 {
679  public:
682 
684  QgsLabelingResults( const QgsLabelingResults & ) = delete;
686  QgsLabelingResults &operator=( const QgsLabelingResults &rh ) = delete;
687 
689  QList<QgsLabelPosition> labelsAtPosition( const QgsPoint &p ) const;
691  QList<QgsLabelPosition> labelsWithinRect( const QgsRectangle &r ) const;
692 
693  private:
694 
695  QgsLabelSearchTree *mLabelSearchTree = nullptr;
696 
697  friend class QgsPalLabeling;
700 };
701 
705 class CORE_EXPORT QgsPalLabeling
706 {
707  public:
708 
711  static bool staticWillUseLayer( QgsVectorLayer *layer );
712 
714  static void drawLabelCandidateRect( pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList<QgsLabelCandidate> *candidates = nullptr );
715 
724  static QgsGeometry prepareGeometry( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, QgsGeometry *clipGeometry = nullptr );
725 
734  static bool geometryRequiresPreparation( const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, QgsGeometry *clipGeometry = nullptr );
735 
743  static QStringList splitToLines( const QString &text, const QString &wrapCharacter );
744 
752  static QStringList splitToGraphemes( const QString &text );
753 
754  protected:
756  static void dataDefinedTextStyle( QgsPalLayerSettings &tmpLyr,
757  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
758 
760  static void dataDefinedTextFormatting( QgsPalLayerSettings &tmpLyr,
761  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
762 
764  static void dataDefinedTextBuffer( QgsPalLayerSettings &tmpLyr,
765  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
766 
768  static void dataDefinedShapeBackground( QgsPalLayerSettings &tmpLyr,
769  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
770 
772  static void dataDefinedDropShadow( QgsPalLayerSettings &tmpLyr,
773  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues );
774 
775  friend class QgsVectorLayerLabelProvider; // to allow calling the static methods above
776  friend class QgsDxfExport; // to allow calling the static methods above
777 
785  static bool checkMinimumSizeMM( const QgsRenderContext &context, const QgsGeometry *geom, double minSize );
786 
787  friend class QgsPalLayerSettings;
788 };
789 
790 #endif // QGSPALLABELING_H
Label below point, slightly right of center.
QgsRectangle labelRect
Class for parsing and evaluation of expressions (formerly called "search strings").
A rectangle specified with double values.
Definition: qgsrectangle.h:38
Label on bottom-left of point.
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...
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:39
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:79
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
QVector< PredefinedPointPosition > predefinedPositionOrder
Ordered list of predefined label positions for points.
QVector< QgsPoint > cornerPoints
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:34
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.
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...
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...
SizeUnit
Units used for option sizes, before being converted to rendered sizes.
A class to represent a point.
Definition: qgspoint.h:37
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. ...
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
QgsLabelPosition(int id, double r, const QVector< QgsPoint > &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())
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.
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.
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...