QGIS API Documentation  3.12.1-BucureČ™ti (121cc00ff0)
qgsvectorlayerlabelprovider.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvectorlayerlabelprovider.cpp
3  --------------------------------------
4  Date : September 2015
5  Copyright : (C) 2015 by Martin Dobias
6  Email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
17 
18 #include "qgsgeometry.h"
19 #include "qgslabelsearchtree.h"
20 #include "qgspallabeling.h"
21 #include "qgstextlabelfeature.h"
22 #include "qgsvectorlayer.h"
24 #include "qgsrenderer.h"
25 #include "qgspolygon.h"
26 #include "qgslinestring.h"
27 #include "qgsmultipolygon.h"
28 #include "qgslogger.h"
30 #include "qgsmaskidprovider.h"
31 
32 #include "feature.h"
33 #include "labelposition.h"
34 #include "callouts/qgscallout.h"
35 
36 #include "pal/layer.h"
37 
38 #include <QPicture>
39 
40 using namespace pal;
41 
42 QgsVectorLayerLabelProvider::QgsVectorLayerLabelProvider( QgsVectorLayer *layer, const QString &providerId, bool withFeatureLoop, const QgsPalLayerSettings *settings, const QString &layerName )
43  : QgsAbstractLabelProvider( layer, providerId )
44  , mSettings( settings ? * settings : QgsPalLayerSettings() ) // TODO: all providers should have valid settings?
45  , mLayerGeometryType( layer->geometryType() )
46  , mRenderer( layer->renderer() )
47  , mFields( layer->fields() )
48  , mCrs( layer->crs() )
49 {
50  mName = layerName.isEmpty() ? layer->id() : layerName;
51 
52  if ( withFeatureLoop )
53  {
54  mSource = qgis::make_unique<QgsVectorLayerFeatureSource>( layer );
55  }
56 
57  init();
58 }
59 
61 {
63  mFlags = Flags();
64  if ( mSettings.drawLabels )
65  mFlags |= DrawLabels;
66  if ( mSettings.displayAll )
72 
73  mPriority = 1 - mSettings.priority / 10.0; // convert 0..10 --> 1..0
74 
76  {
77  //override obstacle type to treat any intersection of a label with the point symbol as a high cost conflict
79  }
80  else
81  {
83  }
84 
86 }
87 
88 
90 {
91  qDeleteAll( mLabels );
92 }
93 
94 
95 bool QgsVectorLayerLabelProvider::prepare( QgsRenderContext &context, QSet<QString> &attributeNames )
96 {
97  const QgsMapSettings &mapSettings = mEngine->mapSettings();
98 
99  return mSettings.prepare( context, attributeNames, mFields, mapSettings, mCrs );
100 }
101 
103 {
105  mSettings.startRender( context );
106 }
107 
109 {
111  mSettings.stopRender( context );
112 }
113 
115 {
116  if ( !mSource )
117  {
118  // we have created the provider with "own feature loop" == false
119  // so it is assumed that prepare() has been already called followed by registerFeature() calls
120  return mLabels;
121  }
122 
123  QSet<QString> attrNames;
124  if ( !prepare( ctx, attrNames ) )
125  return QList<QgsLabelFeature *>();
126 
127  if ( mRenderer )
128  mRenderer->startRender( ctx, mFields );
129 
130  QgsRectangle layerExtent = ctx.extent();
133 
134  QgsFeatureRequest request;
135  request.setFilterRect( layerExtent );
136  request.setSubsetOfAttributes( attrNames, mFields );
137  QgsFeatureIterator fit = mSource->getFeatures( request );
138 
140  ctx.expressionContext().appendScope( symbolScope );
141  QgsFeature fet;
142  while ( fit.nextFeature( fet ) )
143  {
144  QgsGeometry obstacleGeometry;
145  const QgsSymbol *symbol = nullptr;
146  if ( mRenderer )
147  {
148  QgsSymbolList symbols = mRenderer->originalSymbolsForFeature( fet, ctx );
149  if ( !symbols.isEmpty() && fet.geometry().type() == QgsWkbTypes::PointGeometry )
150  {
151  //point feature, use symbol bounds as obstacle
152  obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, ctx, symbols );
153  }
154  if ( !symbols.isEmpty() )
155  {
156  symbol = symbols.at( 0 );
157  symbolScope = QgsExpressionContextUtils::updateSymbolScope( symbol, symbolScope );
158  }
159  }
160  ctx.expressionContext().setFeature( fet );
161  registerFeature( fet, ctx, obstacleGeometry, symbol );
162  }
163 
164  if ( ctx.expressionContext().lastScope() == symbolScope )
165  delete ctx.expressionContext().popScope();
166 
167  if ( mRenderer )
168  mRenderer->stopRender( ctx );
169 
170  return mLabels;
171 }
172 
173 void QgsVectorLayerLabelProvider::registerFeature( const QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry, const QgsSymbol *symbol )
174 {
175  QgsLabelFeature *label = nullptr;
176 
177  mSettings.registerFeature( feature, context, &label, obstacleGeometry, symbol );
178  if ( label )
179  mLabels << label;
180 }
181 
183 {
184  if ( !fet.hasGeometry() || fet.geometry().type() != QgsWkbTypes::PointGeometry )
185  return QgsGeometry();
186 
187  bool isMultiPoint = fet.geometry().constGet()->nCoordinates() > 1;
188  std::unique_ptr< QgsAbstractGeometry > obstacleGeom;
189  if ( isMultiPoint )
190  obstacleGeom = qgis::make_unique< QgsMultiPolygon >();
191 
192  // for each point
193  for ( int i = 0; i < fet.geometry().constGet()->nCoordinates(); ++i )
194  {
195  QRectF bounds;
196  QgsPoint p = fet.geometry().constGet()->vertexAt( QgsVertexId( i, 0, 0 ) );
197  double x = p.x();
198  double y = p.y();
199  double z = 0; // dummy variable for coordinate transforms
200 
201  //transform point to pixels
202  if ( context.coordinateTransform().isValid() )
203  {
204  try
205  {
206  context.coordinateTransform().transformInPlace( x, y, z );
207  }
208  catch ( QgsCsException & )
209  {
210  return QgsGeometry();
211  }
212  }
213  context.mapToPixel().transformInPlace( x, y );
214 
215  QPointF pt( x, y );
216  const auto constSymbols = symbols;
217  for ( QgsSymbol *symbol : constSymbols )
218  {
219  if ( symbol->type() == QgsSymbol::Marker )
220  {
221  if ( bounds.isValid() )
222  bounds = bounds.united( static_cast< QgsMarkerSymbol * >( symbol )->bounds( pt, context, fet ) );
223  else
224  bounds = static_cast< QgsMarkerSymbol * >( symbol )->bounds( pt, context, fet );
225  }
226  }
227 
228  //convert bounds to a geometry
229  QVector< double > bX;
230  bX << bounds.left() << bounds.right() << bounds.right() << bounds.left();
231  QVector< double > bY;
232  bY << bounds.top() << bounds.top() << bounds.bottom() << bounds.bottom();
233  std::unique_ptr< QgsLineString > boundLineString = qgis::make_unique< QgsLineString >( bX, bY );
234 
235  //then transform back to map units
236  //TODO - remove when labeling is refactored to use screen units
237  for ( int i = 0; i < boundLineString->numPoints(); ++i )
238  {
239  QgsPointXY point = context.mapToPixel().toMapCoordinates( static_cast<int>( boundLineString->xAt( i ) ),
240  static_cast<int>( boundLineString->yAt( i ) ) );
241  boundLineString->setXAt( i, point.x() );
242  boundLineString->setYAt( i, point.y() );
243  }
244  if ( context.coordinateTransform().isValid() )
245  {
246  try
247  {
248  boundLineString->transform( context.coordinateTransform(), QgsCoordinateTransform::ReverseTransform );
249  }
250  catch ( QgsCsException & )
251  {
252  return QgsGeometry();
253  }
254  }
255  boundLineString->close();
256 
257  if ( context.coordinateTransform().isValid() )
258  {
259  // coordinate transforms may have resulted in nan coordinates - if so, strip these out
260  boundLineString->filterVertices( []( const QgsPoint & point )->bool
261  {
262  return std::isfinite( point.x() ) && std::isfinite( point.y() );
263  } );
264  if ( !boundLineString->isRing() )
265  return QgsGeometry();
266  }
267 
268  std::unique_ptr< QgsPolygon > obstaclePolygon = qgis::make_unique< QgsPolygon >();
269  obstaclePolygon->setExteriorRing( boundLineString.release() );
270 
271  if ( isMultiPoint )
272  {
273  static_cast<QgsMultiPolygon *>( obstacleGeom.get() )->addGeometry( obstaclePolygon.release() );
274  }
275  else
276  {
277  obstacleGeom = std::move( obstaclePolygon );
278  }
279  }
280 
281  return QgsGeometry( std::move( obstacleGeom ) );
282 }
283 
285 {
286  if ( !mSettings.drawLabels )
287  return;
288 
289  // render callout
291  {
292  drawCallout( context, label );
293  }
294 }
295 
296 void QgsVectorLayerLabelProvider::drawCallout( QgsRenderContext &context, pal::LabelPosition *label ) const
297 {
298  bool enabled = mSettings.callout()->enabled();
300  {
301  context.expressionContext().setOriginalValueVariable( enabled );
303  }
304  if ( enabled )
305  {
306  QgsMapToPixel xform = context.mapToPixel();
307  xform.setMapRotation( 0, 0, 0 );
308  QPointF outPt = xform.transform( label->getX(), label->getY() ).toQPointF();
309  QgsPointXY outPt2 = xform.transform( label->getX() + label->getWidth(), label->getY() + label->getHeight() );
310  QRectF rect( outPt.x(), outPt.y(), outPt2.x() - outPt.x(), outPt2.y() - outPt.y() );
311 
313  g.transform( xform.transform() );
314  QgsCallout::QgsCalloutContext calloutContext;
315  calloutContext.allFeaturePartsLabeled = label->getFeaturePart()->feature()->labelAllParts();
316  mSettings.callout()->render( context, rect, label->getAlpha() * 180 / M_PI, g, calloutContext );
317  }
318 }
319 
321 {
322  if ( !mSettings.drawLabels )
323  return;
324 
325  QgsTextLabelFeature *lf = dynamic_cast<QgsTextLabelFeature *>( label->getFeaturePart()->feature() );
326 
327  // Copy to temp, editable layer settings
328  // these settings will be changed by any data defined values, then used for rendering label components
329  // settings may be adjusted during rendering of components
330  QgsPalLayerSettings tmpLyr( mSettings );
331 
332  // apply any previously applied data defined settings for the label
333  const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues = lf->dataDefinedValues();
334 
335  //font
336  QFont dFont = lf->definedFont();
337  QgsDebugMsgLevel( QStringLiteral( "PAL font tmpLyr: %1, Style: %2" ).arg( tmpLyr.format().font().toString(), tmpLyr.format().font().styleName() ), 4 );
338  QgsDebugMsgLevel( QStringLiteral( "PAL font definedFont: %1, Style: %2" ).arg( dFont.toString(), dFont.styleName() ), 4 );
339 
340  QgsTextFormat format = tmpLyr.format();
341  format.setFont( dFont );
342 
343  // size has already been calculated and stored in the defined font - this calculated size
344  // is in pixels
345  format.setSize( dFont.pixelSize() );
347  tmpLyr.setFormat( format );
348 
350  {
351  //calculate font alignment based on label quadrant
352  switch ( label->getQuadrant() )
353  {
354  case LabelPosition::QuadrantAboveLeft:
355  case LabelPosition::QuadrantLeft:
356  case LabelPosition::QuadrantBelowLeft:
358  break;
359  case LabelPosition::QuadrantAbove:
360  case LabelPosition::QuadrantOver:
361  case LabelPosition::QuadrantBelow:
363  break;
364  case LabelPosition::QuadrantAboveRight:
365  case LabelPosition::QuadrantRight:
366  case LabelPosition::QuadrantBelowRight:
368  break;
369  }
370  }
371 
372  // update tmpLyr with any data defined text style values
373  QgsPalLabeling::dataDefinedTextStyle( tmpLyr, ddValues );
374 
375  // update tmpLyr with any data defined text buffer values
376  QgsPalLabeling::dataDefinedTextBuffer( tmpLyr, ddValues );
377 
378  // update tmpLyr with any data defined text mask values
379  QgsPalLabeling::dataDefinedTextMask( tmpLyr, ddValues );
380 
381  // update tmpLyr with any data defined text formatting values
382  QgsPalLabeling::dataDefinedTextFormatting( tmpLyr, ddValues );
383 
384  // update tmpLyr with any data defined shape background values
385  QgsPalLabeling::dataDefinedShapeBackground( tmpLyr, ddValues );
386 
387  // update tmpLyr with any data defined drop shadow values
388  QgsPalLabeling::dataDefinedDropShadow( tmpLyr, ddValues );
389 
390  // Render the components of a label in reverse order
391  // (backgrounds -> text)
392 
393  // render callout
395  {
396  drawCallout( context, label );
397  }
398 
400  {
401  QgsTextFormat format = tmpLyr.format();
402 
403  if ( tmpLyr.format().background().enabled() && tmpLyr.format().background().type() != QgsTextBackgroundSettings::ShapeMarkerSymbol ) // background shadows not compatible with marker symbol backgrounds
404  {
406  }
407  else if ( tmpLyr.format().buffer().enabled() )
408  {
410  }
411  else
412  {
414  }
415 
416  tmpLyr.setFormat( format );
417  }
418 
419  if ( tmpLyr.format().background().enabled() )
420  {
421  drawLabelPrivate( label, context, tmpLyr, QgsTextRenderer::Background );
422  }
423 
424  if ( tmpLyr.format().buffer().enabled() )
425  {
426  drawLabelPrivate( label, context, tmpLyr, QgsTextRenderer::Buffer );
427  }
428 
429  drawLabelPrivate( label, context, tmpLyr, QgsTextRenderer::Text );
430 
431  // add to the results
432  QString labeltext = label->getFeaturePart()->feature()->labelText();
433  mEngine->results()->mLabelSearchTree->insertLabel( label, label->getFeaturePart()->featureId(), mLayerId, labeltext, dFont, false, lf->hasFixedPosition(), mProviderId );
434 }
435 
437 {
438  if ( !mSettings.drawLabels )
439  return;
440 
441  QgsTextLabelFeature *lf = dynamic_cast<QgsTextLabelFeature *>( label->getFeaturePart()->feature() );
442 
443  QgsPalLayerSettings tmpLyr( mSettings );
444  QgsTextFormat format = tmpLyr.format();
446  tmpLyr.setFormat( format );
447  drawLabelPrivate( label, context, tmpLyr, QgsTextRenderer::Text );
448 
449  // add to the results
450  QString labeltext = label->getFeaturePart()->feature()->labelText();
451  mEngine->results()->mLabelSearchTree->insertLabel( label, label->getFeaturePart()->featureId(), mLayerId, labeltext, tmpLyr.format().font(), false, lf->hasFixedPosition(), mProviderId, true );
452 }
453 
455 {
456  // NOTE: this is repeatedly called for multi-part labels
457  QPainter *painter = context.painter();
458 
459  // features are pre-rotated but not scaled/translated,
460  // so we only disable rotation here. Ideally, they'd be
461  // also pre-scaled/translated, as suggested here:
462  // https://github.com/qgis/QGIS/issues/20071
463  QgsMapToPixel xform = context.mapToPixel();
464  xform.setMapRotation( 0, 0, 0 );
465 
466  QPointF outPt = xform.transform( label->getX(), label->getY() ).toQPointF();
467 
468  if ( mEngine->engineSettings().testFlag( QgsLabelingEngineSettings::DrawLabelRectOnly ) ) // TODO: this should get directly to labeling engine
469  {
470  //debugging rect
471  if ( drawType != QgsTextRenderer::Text )
472  return;
473 
474  QgsPointXY outPt2 = xform.transform( label->getX() + label->getWidth(), label->getY() + label->getHeight() );
475  QRectF rect( 0, 0, outPt2.x() - outPt.x(), outPt2.y() - outPt.y() );
476  painter->save();
477  painter->setRenderHint( QPainter::Antialiasing, false );
478  painter->translate( QPointF( outPt.x(), outPt.y() ) );
479  painter->rotate( -label->getAlpha() * 180 / M_PI );
480 
481  if ( label->conflictsWithObstacle() )
482  {
483  painter->setBrush( QColor( 255, 0, 0, 100 ) );
484  painter->setPen( QColor( 255, 0, 0, 150 ) );
485  }
486  else
487  {
488  painter->setBrush( QColor( 0, 255, 0, 100 ) );
489  painter->setPen( QColor( 0, 255, 0, 150 ) );
490  }
491 
492  painter->drawRect( rect );
493  painter->restore();
494 
495  if ( label->nextPart() )
496  drawLabelPrivate( label->nextPart(), context, tmpLyr, drawType, dpiRatio );
497 
498  return;
499  }
500 
501  QgsTextRenderer::Component component;
502  component.dpiRatio = dpiRatio;
503  component.origin = outPt;
504  component.rotation = label->getAlpha();
505 
506 
507 
508  if ( drawType == QgsTextRenderer::Background )
509  {
510  // get rotated label's center point
511  QPointF centerPt( outPt );
512  QgsPointXY outPt2 = xform.transform( label->getX() + label->getWidth() / 2,
513  label->getY() + label->getHeight() / 2 );
514 
515  double xc = outPt2.x() - outPt.x();
516  double yc = outPt2.y() - outPt.y();
517 
518  double angle = -component.rotation;
519  double xd = xc * std::cos( angle ) - yc * std::sin( angle );
520  double yd = xc * std::sin( angle ) + yc * std::cos( angle );
521 
522  centerPt.setX( centerPt.x() + xd );
523  centerPt.setY( centerPt.y() + yd );
524 
525  component.center = centerPt;
526 
527  // convert label size to render units
528  double labelWidthPx = context.convertToPainterUnits( label->getWidth(), QgsUnitTypes::RenderMapUnits, QgsMapUnitScale() );
529  double labelHeightPx = context.convertToPainterUnits( label->getHeight(), QgsUnitTypes::RenderMapUnits, QgsMapUnitScale() );
530 
531  component.size = QSizeF( labelWidthPx, labelHeightPx );
532 
533  QgsTextRenderer::drawBackground( context, component, tmpLyr.format(), QStringList(), QgsTextRenderer::Label );
534  }
535 
536  else if ( drawType == QgsTextRenderer::Buffer
537  || drawType == QgsTextRenderer::Text )
538  {
539 
540  // TODO: optimize access :)
541  QgsTextLabelFeature *lf = static_cast<QgsTextLabelFeature *>( label->getFeaturePart()->feature() );
542  QString txt = lf->text( label->getPartId() );
543  QFontMetricsF *labelfm = lf->labelFontMetrics();
544 
545  if ( context.maskIdProvider() )
546  {
547  int maskId = context.maskIdProvider()->maskId( label->getFeaturePart()->layer()->provider()->layerId(),
548  label->getFeaturePart()->layer()->provider()->providerId() );
549  context.setCurrentMaskId( maskId );
550  }
551 
552  //add the direction symbol if needed
553  if ( !txt.isEmpty() && tmpLyr.placement == QgsPalLayerSettings::Line &&
554  tmpLyr.addDirectionSymbol )
555  {
556  bool prependSymb = false;
557  QString symb = tmpLyr.rightDirectionSymbol;
558 
559  if ( label->getReversed() )
560  {
561  prependSymb = true;
562  symb = tmpLyr.leftDirectionSymbol;
563  }
564 
565  if ( tmpLyr.reverseDirectionSymbol )
566  {
567  if ( symb == tmpLyr.rightDirectionSymbol )
568  {
569  prependSymb = true;
570  symb = tmpLyr.leftDirectionSymbol;
571  }
572  else
573  {
574  prependSymb = false;
575  symb = tmpLyr.rightDirectionSymbol;
576  }
577  }
578 
580  {
581  prependSymb = true;
582  symb = symb + QStringLiteral( "\n" );
583  }
585  {
586  prependSymb = false;
587  symb = QStringLiteral( "\n" ) + symb;
588  }
589 
590  if ( prependSymb )
591  {
592  txt.prepend( symb );
593  }
594  else
595  {
596  txt.append( symb );
597  }
598  }
599 
600  //QgsDebugMsgLevel( "drawLabel " + txt, 4 );
601  QStringList multiLineList = QgsPalLabeling::splitToLines( txt, tmpLyr.wrapChar, tmpLyr.autoWrapLength, tmpLyr.useMaxLineLengthForAutoWrap );
602 
606  else if ( tmpLyr.multilineAlign == QgsPalLayerSettings::MultiRight )
608 
609  QgsTextRenderer::Component component;
610  component.origin = outPt;
611  component.rotation = label->getAlpha();
612 
613  QgsTextRenderer::drawTextInternal( drawType, context, tmpLyr.format(), component, multiLineList, labelfm,
614  hAlign, QgsTextRenderer::Label );
615 
616  }
617 
618  // NOTE: this used to be within above multi-line loop block, at end. (a mistake since 2010? [LS])
619  if ( label->nextPart() )
620  drawLabelPrivate( label->nextPart(), context, tmpLyr, drawType, dpiRatio );
621 }
622 
624 {
625  return mSettings;
626 }
QgsAbstractLabelProvider * provider() const
Returns pointer to the associated provider.
Definition: layer.h:166
QList< QgsLabelFeature * > mLabels
List of generated.
QColor unplacedLabelColor() const
Returns the color to use when rendering unplaced labels.
LabelPosition * nextPart() const
Returns the next part of this label position (i.e.
static QgsExpressionContextScope * updateSymbolScope(const QgsSymbol *symbol, QgsExpressionContextScope *symbolScope=nullptr)
Updates a symbol scope related to a QgsSymbol to an expression context.
Wrapper for iterator of features from vector data provider or vector layer.
QgsLabelObstacleSettings::ObstacleType mObstacleType
Type of the obstacle of feature geometries.
QgsVectorLayerLabelProvider(QgsVectorLayer *layer, const QString &providerId, bool withFeatureLoop, const QgsPalLayerSettings *settings, const QString &layerName=QString())
Convenience constructor to initialize the provider from given vector layer.
QString labelText() const
Text of the label.
A rectangle specified with double values.
Definition: qgsrectangle.h:41
double y
Definition: qgspoint.h:42
QString leftDirectionSymbol
String to use for left direction arrows.
QgsWkbTypes::GeometryType mLayerGeometryType
Geometry type of layer.
void setMapRotation(double degrees, double cx, double cy)
Set map rotation in degrees (clockwise)
QgsTextShadowSettings::ShadowPlacement shadowPlacement() const
Returns the placement for the drop shadow.
QgsPalLayerSettings::Placement mPlacement
Placement strategy.
void registerFeature(const QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **labelFeature=nullptr, QgsGeometry obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling.
QgsFeatureId featureId() const
Returns the unique ID of the feature.
Definition: feature.cpp:156
Abstract base class for all rendered symbols.
Definition: qgssymbol.h:62
void render(QgsRenderContext &context, QRectF rect, const double angle, const QgsGeometry &anchor, QgsCalloutContext &calloutContext)
Renders the callout onto the specified render context.
Definition: qgscallout.cpp:109
std::unique_ptr< QgsAbstractFeatureSource > mSource
Layer&#39;s feature source.
QgsLabelFeature * feature()
Returns the parent feature.
Definition: feature.h:117
virtual bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
const QgsLabelingEngine * mEngine
Associated labeling engine.
Contains additional contextual information about the context in which a callout is being rendered...
Definition: qgscallout.h:195
Draw shadow under buffer.
UpsideDownLabels upsidedownLabels
Controls whether upside down labels are displayed and how they are handled.
Place direction symbols on below label.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
double mPriority
Default priority of labels.
QgsTextShadowSettings & shadow()
Returns a reference to the text drop shadow settings.
double getY(int i=0) const
Returns the down-left y coordinate.
double y
Definition: qgspointxy.h:48
A class to represent a 2D point.
Definition: qgspointxy.h:43
HAlignment
Horizontal alignment.
void setFont(const QFont &font)
Sets the font used for rendering text.
void stopRender(QgsRenderContext &context) override
To be called after rendering is complete.
const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > & dataDefinedValues() const
Gets data-defined values.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
Class that adds extra information to QgsLabelFeature for text labels.
GEOSGeometry * geometry() const
Gets access to the associated geometry.
bool addDirectionSymbol
If true, &#39;<&#39; or &#39;>&#39; (or custom strings set via leftDirectionSymbol and rightDirectionSymbol) will be ...
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:122
Whether to only draw the label rect and not the actual label text (used for unit tests) ...
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 ...
MultiLineAlign multilineAlign
Horizontal alignment of multi-line labels.
virtual DrawOrder drawOrder() const
Returns the desired drawing order (stacking) to use while rendering this callout. ...
Definition: qgscallout.cpp:104
Label-specific draw mode.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:55
const QgsCoordinateReferenceSystem & crs
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:197
int autoWrapLength
If non-zero, indicates that label text should be automatically wrapped to (ideally) the specified num...
QgsCoordinateTransform ct
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored)
Definition: MathUtils.cpp:786
bool reverseDirectionSymbol
True if direction symbols should be reversed.
A marker symbol type, for rendering Point and MultiPoint geometries.
Definition: qgssymbol.h:895
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
ShapeType type() const
Returns the type of background shape (e.g., square, ellipse, SVG).
void setFormat(const QgsTextFormat &format)
Sets the label text formatting settings, e.g., font settings, buffer settings, etc.
virtual QgsSymbolList originalSymbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const
Equivalent of originalSymbolsForFeature() call extended to support renderers that may use more symbol...
bool isActive(int key) const override
Returns true if the collection contains an active property with the specified key.
Whether adjacent lines (with the same label text) should be merged.
The QgsMapSettings class contains configuration for rendering of the map.
QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &context) override
Returns list of label features (they are owned by the provider and thus deleted on its destruction) ...
QgsMapLayer * layer() const
Returns the associated layer, or nullptr if no layer is associated with the provider.
void transformInPlace(double &x, double &y) const
Transform device coordinates to map coordinates.
void init()
initialization method - called from constructors
void setCurrentMaskId(int id)
Stores a mask id as the "current" one.
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:37
QgsPointXY transform(const QgsPointXY &p) const
Transform the point from map (world) coordinates to device coordinates.
QgsExpressionContextScope * lastScope()
Returns the last scope added to the context.
QList< QgsSymbol * > QgsSymbolList
Definition: qgsrenderer.h:45
bool displayAll
If true, all features will be labelled even when overlaps occur.
void setSize(double size)
Sets the size for rendered text.
QString id() const
Returns the layer&#39;s unique ID, which is used to access this layer from QgsProject.
const QgsLabelingEngineSettings & engineSettings() const
Gets associated labeling engine settings.
static std::unique_ptr< QgsAbstractGeometry > fromGeos(const GEOSGeometry *geos)
Create a geometry from a GEOSGeometry.
Definition: qgsgeos.cpp:1081
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
Utility class for identifying a unique vertex within a geometry.
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
Render callouts below their individual associated labels, some callouts may be drawn over other label...
Definition: qgscallout.h:82
const QgsRectangle & extent() const
When rendering a map layer, calling this method returns the "clipping" extent for the layer (in the l...
bool isShortCircuited() const
Returns true if the transform short circuits because the source and destination are equivalent...
Buffer component.
double getHeight() const
QgsPalLayerSettings mSettings
Layer&#39;s labeling configuration.
const QgsPalLayerSettings & settings() const
Returns the layer&#39;s settings.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
Layer * layer()
Returns the layer that feature belongs to.
Definition: feature.cpp:151
This class wraps a request for features to a vector layer (or directly its vector data provider)...
Flags mFlags
Flags altering drawing and registration of features.
Draw shadow under text.
Whether location of centroid must be inside of polygons.
bool allFeaturePartsLabeled
true if all parts of associated feature were labeled
Definition: qgscallout.h:198
Quadrant getQuadrant() const
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
QgsTextBackgroundSettings & background()
Returns a reference to the text background settings.
QgsTextBufferSettings & buffer()
Returns a reference to the text buffer settings.
void setSizeUnit(QgsUnitTypes::RenderUnit unit)
Sets the units for the size of rendered text.
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
QString text(int partId) const
Returns the text component corresponding to a specified label part.
Whether all features will be labelled even though overlaps occur.
Single scope for storing variables and functions for use within a QgsExpressionContext.
Render callouts below all labels.
Definition: qgscallout.h:81
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:37
The QgsAbstractLabelProvider class is an interface class.
QString layerId() const
Returns ID of associated layer, or empty string if no layer is associated with the provider...
const QgsTextFormat & format() const
Returns the label text formatting settings, e.g., font settings, buffer settings, etc...
double x
Definition: qgspointxy.h:47
Place direction symbols on above label.
Draw shadow below all text components.
virtual void registerFeature(const QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling as one or more QgsLabelFeature objects stored into mLabels...
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsExpressionContext & expressionContext()
Gets the expression context.
void transformInPlace(double &x, double &y, double &z, TransformDirection direction=ForwardTransform) const SIP_THROW(QgsCsException)
Transforms an array of x, y and z double coordinates in place, from the source CRS to the destination...
QString wrapChar
Wrapping character string.
bool valueAsBool(int key, const QgsExpressionContext &context, bool defaultValue=false, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as an boolean...
TextPart
Components of text.
QgsFields mFields
Layer&#39;s fields.
QString rightDirectionSymbol
String to use for right direction arrows.
Marker symbol.
Definition: qgssymbol.h:86
Arranges candidates parallel to a generalised line representing the feature or parallel to a polygon&#39;...
Contains information about the context of a rendering operation.
double convertToPainterUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to painter units (pixels).
QFont definedFont()
Font to be used for rendering.
bool enabled() const
Returns true if the the callout is enabled.
Definition: qgscallout.h:228
bool hasFixedPosition() const
Whether the label should use a fixed position instead of being automatically placed.
QPainter * painter()
Returns the destination QPainter for the render operation.
The QgsLabelFeature class describes a feature that should be used within the labeling engine...
const QgsMapToPixel & mapToPixel() const
Returns the context&#39;s map to pixel transform, which transforms between map coordinates and device coo...
Transform from destination to source CRS.
double getAlpha() const
Returns the angle to rotate text (in rad).
Multi polygon geometry collection.
QString mName
Name of the layer.
bool enabled() const
Returns whether the shadow is enabled.
Struct for storing maximum and minimum scales for measurements in map units.
QgsCoordinateReferenceSystem mCrs
Layer&#39;s CRS.
double getWidth() const
bool conflictsWithObstacle() const
Returns whether the position is marked as conflicting with an obstacle feature.
double getX(int i=0) const
Returns the down-left x coordinate.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
Definition: qgsrenderer.cpp:93
const QgsLabelObstacleSettings & obstacleSettings() const
Returns the label obstacle settings.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
const QgsMapSettings & mapSettings() const
Gets associated map settings.
bool enabled() const
Returns whether the background is enabled.
bool testFlag(Flag f) const
Test whether a particular flag is enabled.
int maskId(const QString &labelLayerId=QString(), const QString &labelRuleId=QString()) const
Returns the mask id associated with a label layer and its optional label rule.
QgsLabelingResults * results() const
For internal use by the providers.
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
QString mProviderId
Associated provider ID (one layer may have multiple providers, e.g. in rule-based labeling) ...
LabelPosition is a candidate feature label position.
Definition: labelposition.h:55
virtual void startRender(QgsRenderContext &context)
To be called before rendering of labels begins.
bool enabled() const
Returns whether the buffer is enabled.
QgsPalLayerSettings::UpsideDownLabels mUpsidedownLabels
How to handle labels that would be upside down.
void setShadowPlacement(QgsTextShadowSettings::ShadowPlacement placement)
Sets the placement for the drop shadow.
QString providerId() const
Returns provider ID - useful in case there is more than one label provider within a layer (e...
Draw shadow under background shape.
void startRender(QgsRenderContext &context)
Prepares the label settings for rendering.
QgsCallout * callout() const
Returns the label callout renderer, responsible for drawing label callouts.
Whether the labels should be rendered.
QgsWkbTypes::GeometryType type
Definition: qgsgeometry.h:126
QgsGeometry geometry
Definition: qgsfeature.h:67
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:65
ObstacleType type() const
Returns how features act as obstacles for labels.
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
bool getReversed() const
bool nextFeature(QgsFeature &f)
void drawLabelBackground(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw the background for the specified label.
void startRender(QgsRenderContext &context) override
To be called before rendering of labels begins.
Container for all settings relating to text rendering.
QFontMetricsF * labelFontMetrics()
Metrics of the font for rendering.
bool centroidInside
true if centroid positioned labels must be placed inside their corresponding feature polygon...
virtual void stopRender(QgsRenderContext &context)
To be called after rendering is complete.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
virtual int nCoordinates() const
Returns the number of nodes contained in the geometry.
Represents a vector layer which manages a vector based data sets.
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
QString mLayerId
Associated layer&#39;s ID, if applicable.
bool labelAllParts() const
Returns true if all parts of the feature should be labeled.
QFont font() const
Returns the font used for rendering text.
bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames, const QgsFields &fields, const QgsMapSettings &mapSettings, const QgsCoordinateReferenceSystem &crs)
Prepare for registration of features.
int priority
Label priority.
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
void drawLabel(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw this label at the position determined by the labeling engine.
void drawLabelPrivate(pal::LabelPosition *label, QgsRenderContext &context, QgsPalLayerSettings &tmpLyr, QgsTextRenderer::TextPart drawType, double dpiRatio=1.0) const
Internal label drawing method.
bool useMaxLineLengthForAutoWrap
If true, indicates that when auto wrapping label text the autoWrapLength length indicates the maximum...
int getPartId() const
static QStringList splitToLines(const QString &text, const QString &wrapCharacter, int autoWrapLength=0, bool useMaxLineLengthWhenAutoWrapping=true)
Splits a text string to a list of separate lines, using a specified wrap character (wrapCharacter)...
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, TransformDirection direction=ForwardTransform, bool handle180Crossover=false) const SIP_THROW(QgsCsException)
Transforms a rectangle from the source CRS to the destination CRS.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label&#39;s property collection, used for data defined overrides.
const QgsMaskIdProvider * maskIdProvider() const
Returns the mask id provider attached to the context.
static QgsGeometry getPointObstacleGeometry(QgsFeature &fet, QgsRenderContext &context, const QgsSymbolList &symbols)
Returns the geometry for a point feature which should be used as an obstacle for labels.
void stopRender(QgsRenderContext &context)
Finalises the label settings after use.
DirectionSymbols placeDirectionSymbol
Placement option for direction symbols.
void drawUnplacedLabel(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw an unplaced label.
double x
Definition: qgspoint.h:41