56#include <QApplication>
58#include <QFontMetrics>
63#include <QTextBoundaryFinder>
67using namespace Qt::StringLiterals;
84 DEFAULT_PLACEMENT_ORDER,
104void QgsPalLayerSettings::initPropertyDefinitions()
106 if ( !sPropertyDefinitions()->isEmpty() )
109 const QString origin = u
"labeling"_s;
119 QgsPropertyDefinition(
122 QObject::tr(
"Font family" ),
123 QObject::tr(
"string " )
125 "[<b>family</b>|<b>family[foundry]</b>],<br>"
126 "e.g. Helvetica or Helvetica [Cronyx]"
131 QgsPropertyDefinition(
134 QObject::tr(
"Font style" ),
135 QObject::tr(
"string " )
137 "[<b>font style name</b>|<b>Ignore</b>],<br>"
138 "e.g. Bold Condensed or Light Italic"
148 QgsPropertyDefinition(
"FontCase",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Font case" ), QObject::tr(
"string " ) + u
"[<b>NoChange</b>|<b>Upper</b>|<br><b>Lower</b>|<b>Title</b>|<b>Capitalize</b>|<b>SmallCaps</b>|<b>AllSmallCaps</b>]"_s, origin ) },
157 QgsPropertyDefinition(
"MultiLineAlignment",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Line alignment" ), QObject::tr(
"string " ) +
"[<b>Left</b>|<b>Center</b>|<b>Right</b>|<b>Follow</b>]", origin ) },
159 QgsPropertyDefinition(
"TabStopDistance",
QgsPropertyDefinition::DataTypeNumeric, QObject::tr(
"Tab stop distance(s)" ), QObject::tr(
"Numeric distance or array of distances" ), origin ) },
161 QgsPropertyDefinition(
"TextOrientation",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Text orientation" ), QObject::tr(
"string " ) +
"[<b>Horizontal</b>|<b>Vertical</b>|<b>RotationBased</b>]", origin ) },
166 QgsPropertyDefinition(
"DirSymbPlacement",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Direction symbol placement" ), QObject::tr(
"string " ) +
"[<b>LeftRight</b>|<b>Above</b>|<b>Below</b>]", origin ) },
189 QgsPropertyDefinition(
192 QObject::tr(
"Shape type" ),
193 QObject::tr(
"string " )
195 "[<b>Rectangle</b>|<b>Square</b>|<br>"
196 "<b>Ellipse</b>|<b>Circle</b>|<b>SVG</b>]"
202 QgsPropertyDefinition(
"ShapeSizeType",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Shape size type" ), QObject::tr(
"string " ) +
"[<b>Buffer</b>|<b>Fixed</b>]", origin ) },
207 QgsPropertyDefinition(
"ShapeRotationType",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Shape rotation type" ), QObject::tr(
"string " ) +
"[<b>Sync</b>|<b>Offset</b>|<b>Fixed</b>]", origin ) },
227 QgsPropertyDefinition(
230 QObject::tr(
"Symbol size" ),
231 QObject::tr(
"string " )
233 "[<b>Lowest</b>|<b>Text</b>|<br>"
234 "<b>Buffer</b>|<b>Background</b>]"
255 QgsPropertyDefinition(
"CentroidWhole",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Centroid of whole shape" ), QObject::tr(
"string " ) +
"[<b>Visible</b>|<b>Whole</b>]", origin ) },
257 QgsPropertyDefinition(
260 QObject::tr(
"Offset quadrant" ),
261 QObject::tr(
"int<br>" )
263 "[<b>0</b>=Above Left|<b>1</b>=Above|<b>2</b>=Above Right|<br>"
264 "<b>3</b>=Left|<b>4</b>=Over|<b>5</b>=Right|<br>"
265 "<b>6</b>=Below Left|<b>7</b>=Below|<b>8</b>=Below Right]"
275 QgsPropertyDefinition(
"CurvedCharAngleInOut",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Curved character angles" ), QObject::tr(
"double coord [<b>in,out</b> as 20.0-60.0,20.0-95.0]" ), origin ) },
283 QgsPropertyDefinition(
"LineAnchorClipping",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Line anchor clipping mode" ), QObject::tr(
"string " ) + u
"[<b>Visible</b>|<b>Entire</b>]"_s, origin ) },
285 QgsPropertyDefinition(
"LineAnchorType",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Line anchor type" ), QObject::tr(
"string " ) + u
"[<b>Hint</b>|<b>Strict</b>]"_s, origin ) },
287 QgsPropertyDefinition(
"LineAnchorTextPoint",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Line anchor text point" ), QObject::tr(
"string " ) + u
"[<b>Follow</b>|<b>Start</b>|<b>Center</b>|<b>End</b>]"_s, origin ) },
289 QgsPropertyDefinition(
"CurvedLabelMode",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Curved label mode" ), QObject::tr(
"string " ) + u
"[<b>Default</b>|<b>CharactersAtVertices</b>|<b>StretchCharacterSpacingToFit</b>|<b>StretchWordSpacingToFit</b>]"_s, origin ) },
296 QgsPropertyDefinition(
297 "PredefinedPositionOrder",
299 QObject::tr(
"Predefined position order" ),
300 QObject::tr(
"Comma separated list of placements in order of priority<br>" )
302 "[<b>TopLeft</b>=Top left|<b>TopSlightyLeft</b>=Top, slightly left|<b>Top</b>=Top middle|<br>"
303 "<b>TopSlightlyRight</b>=Top, slightly right|<b>TopRight</b>=Top right|<br>"
304 "<b>Left</b>=Left|<b>Right</b>=Right|<br>"
305 "<b>BottomLeft</b>=Bottom left|<b>BottomSlightlyLeft</b>=Bottom, slightly left|<b>Bottom</b>=Bottom middle|<br>"
306 "<b>BottomSlightlyRight</b>=Bottom, slightly right|<b>BottomRight</b>=Bottom right|<b>OverPoint</b>=Over point]"
311 QgsPropertyDefinition(
312 "LinePlacementFlags",
314 QObject::tr(
"Line placement options" ),
315 QObject::tr(
"Comma separated list of placement options<br>" )
317 "[<b>OnLine</b>=On line|<b>AboveLine</b>=Above line|<b>BelowLine</b>=Below line|<br>"
318 "<b>LineOrientation</b>=Respect line orientation]"
323 QgsPropertyDefinition(
"PolygonLabelOutside",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Label outside polygons" ), QObject::tr(
"string " ) +
"[<b>Yes</b> (allow placing outside)|<b>No</b> (never place outside)|<b>Force</b> (always place outside)]", origin ) },
329 QgsPropertyDefinition(
"Hali",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Horizontal alignment" ), QObject::tr(
"string " ) +
"[<b>Left</b>|<b>Center</b>|<b>Right</b>]", origin ) },
331 QgsPropertyDefinition(
334 QObject::tr(
"Vertical alignment" ),
335 QObject::tr(
"string " )
337 "[<b>Bottom</b>|<b>Base</b>|<br>"
338 "<b>Half</b>|<b>Cap</b>|<b>Top</b>]"
358 QgsPropertyDefinition(
"LabelAllParts",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Multipart geometry behavior" ), QObject::tr(
"string " ) +
"[<b>LargestPartOnly</b>|<b>LabelEveryPart</b>|<b>SplitLabelTextLinesOverParts</b>]", origin ) },
362 QgsPropertyDefinition(
"OverlapHandling",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Overlap handling" ), QObject::tr(
"string " ) +
"[<b>Prevent</b>|<b>AllowIfNeeded</b>|<b>AlwaysAllow</b>]", origin ) },
365 QgsPropertyDefinition(
"WhitespaceCollisionHandling",
QgsPropertyDefinition::DataTypeString, QObject::tr(
"Whitespace collision handling" ), QObject::tr(
"string " ) + u
"[<b>TreatWhitespaceAsCollision</b>|<b>IgnoreWhitespaceCollisions</b>]"_s, origin ) },
383 mPointSettings.setPredefinedPositionOrder( *DEFAULT_PLACEMENT_ORDER() );
385 initPropertyDefinitions();
393 : mDataDefinedProperties( s.mDataDefinedProperties )
428 mPolygonPlacementFlags = s.mPolygonPlacementFlags;
442 mRotationUnit = s.mRotationUnit;
462 mDataDefinedProperties = s.mDataDefinedProperties;
464 mCallout.reset( s.mCallout ? s.mCallout->clone() :
nullptr );
466 mPlacementSettings = s.mPlacementSettings;
467 mLineSettings = s.mLineSettings;
468 mPointSettings = s.mPointSettings;
469 mObstacleSettings = s.mObstacleSettings;
470 mThinningSettings = s.mThinningSettings;
477 mLegendString = s.mLegendString;
479 mUnplacedVisibility = s.mUnplacedVisibility;
514 if (
drawLabels || mObstacleSettings.isObstacle() )
529 for (
const QString &name : referencedColumns )
531 attributeNames.insert( name );
588 if ( mGeometryGeneratorExpression.hasParserError() )
594 const auto referencedColumns = mGeometryGeneratorExpression.referencedColumns();
595 for (
const QString &name : referencedColumns )
597 attributeNames.insert( name );
600 attributeNames.unite( mFormat.referencedFields( context ) );
604 const auto referencedColumns = mCallout->referencedFields( context );
605 for (
const QString &name : referencedColumns )
607 attributeNames.insert( name );
616 QSet<QString> referenced;
629 referenced.unite( mFormat.referencedFields( context ) );
634 referenced.unite( mDataDefinedProperties.referencedFields( context.
expressionContext(),
true ) );
644 referenced.unite( mCallout->referencedFields( context ) );
652 if ( mRenderStarted )
654 qWarning(
"Start render called for when a previous render was already underway!!" );
681 mCallout->startRender( context );
684 mRenderStarted =
true;
689 if ( !mRenderStarted )
691 qWarning(
"Stop render called for QgsPalLayerSettings without a startRender call!" );
697 mCallout->stopRender( context );
700 mRenderStarted =
false;
705 return mFormat.containsAdvancedEffects() || mCallout->containsAdvancedEffects();
710 if ( mRenderStarted )
712 qWarning(
"stopRender was not called on QgsPalLayerSettings object!" );
719 initPropertyDefinitions();
720 return *sPropertyDefinitions();
727 expression = std::make_unique<QgsExpression>(
fieldName );
729 return expression.get();
734 return mRotationUnit;
739 mRotationUnit = angleUnit;
745 QString newValue = value;
746 if ( !value.isEmpty() && !value.contains(
"~~"_L1 ) )
753 newValue = values.join(
"~~"_L1 );
761 QString newPropertyName =
"labeling/dataDefined/" + sPropertyDefinitions()->value(
static_cast< int >( p ) ).name();
762 QVariant newPropertyField = layer->
customProperty( newPropertyName, QVariant() );
764 if ( !newPropertyField.isValid() )
767 QString ddString = newPropertyField.toString();
769 if ( !ddString.isEmpty() && ddString !=
"0~~0~~~~"_L1 )
773 QStringList ddv = newStyleString.split( u
"~~"_s );
775 bool active = ddv.at( 0 ).toInt();
776 if ( ddv.at( 1 ).toInt() )
792void QgsPalLayerSettings::readOldDataDefinedPropertyMap(
QgsVectorLayer *layer, QDomElement *parentElem )
794 if ( !layer && !parentElem )
799 QgsPropertiesDefinition::const_iterator i = sPropertyDefinitions()->constBegin();
800 for ( ; i != sPropertyDefinitions()->constEnd(); ++i )
805 readOldDataDefinedProperty( layer,
static_cast< Property >( i.key() ) );
807 else if ( parentElem )
810 QDomElement e = parentElem->firstChildElement( i.value().name() );
813 bool active = e.attribute( u
"active"_s ).compare(
"true"_L1, Qt::CaseInsensitive ) == 0;
814 bool isExpression = e.attribute( u
"useExpr"_s ).compare(
"true"_L1, Qt::CaseInsensitive ) == 0;
821 mDataDefinedProperties.setProperty( i.key(),
QgsProperty::fromField( e.attribute( u
"field"_s ), active ) );
828void QgsPalLayerSettings::readFromLayerCustomProperties(
QgsVectorLayer *layer )
830 if ( layer->
customProperty( u
"labeling"_s ).toString() !=
"pal"_L1 )
847 mFormat.readFromLayer( layer );
855 QDomDocument doc( u
"substitutions"_s );
856 doc.setContent( layer->
customProperty( u
"labeling/substitutions"_s ).toString() );
857 QDomElement replacementElem = doc.firstChildElement( u
"substitutions"_s );
869 mLineSettings.setAddDirectionSymbol( layer->
customProperty( u
"labeling/addDirectionSymbol"_s ).toBool() );
870 mLineSettings.setLeftDirectionSymbol( layer->
customProperty( u
"labeling/leftDirectionSymbol"_s, QVariant(
"<" ) ).toString() );
871 mLineSettings.setRightDirectionSymbol( layer->
customProperty( u
"labeling/rightDirectionSymbol"_s, QVariant(
">" ) ).toString() );
872 mLineSettings.setReverseDirectionSymbol( layer->
customProperty( u
"labeling/reverseDirectionSymbol"_s ).toBool() );
873 mLineSettings.setDirectionSymbolPlacement(
889 if ( predefinedPositionOrder.isEmpty() )
890 predefinedPositionOrder = *DEFAULT_PLACEMENT_ORDER();
891 mPointSettings.setPredefinedPositionOrder( predefinedPositionOrder );
896 if ( layer->
customProperty( u
"labeling/distMapUnitScale"_s ).toString().isEmpty() )
899 double oldMin = layer->
customProperty( u
"labeling/distMapUnitMinScale"_s, 0.0 ).toDouble();
901 double oldMax = layer->
customProperty( u
"labeling/distMapUnitMaxScale"_s, 0.0 ).toDouble();
909 mPointSettings.setQuadrant(
914 if ( layer->
customProperty( u
"labeling/labelOffsetInMapUnits"_s, QVariant(
true ) ).toBool() )
919 if ( layer->
customProperty( u
"labeling/labelOffsetMapUnitScale"_s ).toString().isEmpty() )
922 double oldMin = layer->
customProperty( u
"labeling/labelOffsetMapUnitMinScale"_s, 0.0 ).toDouble();
924 double oldMax = layer->
customProperty( u
"labeling/labelOffsetMapUnitMaxScale"_s, 0.0 ).toDouble();
932 QVariant tempAngle = layer->
customProperty( u
"labeling/angleOffset"_s, QVariant() );
933 if ( tempAngle.isValid() )
935 double oldAngle = layer->
customProperty( u
"labeling/angleOffset"_s, QVariant( 0.0 ) ).toDouble();
949 switch ( layer->
customProperty( u
"labeling/repeatDistanceUnit"_s, QVariant( 1 ) ).toUInt() )
964 if ( layer->
customProperty( u
"labeling/repeatDistanceMapUnitScale"_s ).toString().isEmpty() )
967 double oldMin = layer->
customProperty( u
"labeling/repeatDistanceMapUnitMinScale"_s, 0.0 ).toDouble();
969 double oldMax = layer->
customProperty( u
"labeling/repeatDistanceMapUnitMaxScale"_s, 0.0 ).toDouble();
978 double scalemn = layer->
customProperty( u
"labeling/scaleMin"_s, QVariant( 0 ) ).toDouble();
979 double scalemx = layer->
customProperty( u
"labeling/scaleMax"_s, QVariant( 0 ) ).toDouble();
982 QVariant scalevis = layer->
customProperty( u
"labeling/scaleVisibility"_s, QVariant() );
983 if ( scalevis.isValid() )
989 else if ( scalemn > 0 || scalemx > 0 )
1005 if ( layer->
customProperty( u
"labeling/displayAll"_s, QVariant(
false ) ).toBool() )
1008 mPlacementSettings.setAllowDegradedPlacement(
true );
1013 mPlacementSettings.setAllowDegradedPlacement(
false );
1019 mLineSettings.setMergeLines( layer->
customProperty( u
"labeling/mergeLines"_s ).toBool() );
1020 mThinningSettings.setMinimumFeatureSize( layer->
customProperty( u
"labeling/minFeatureSize"_s ).toDouble() );
1021 mThinningSettings.setLimitNumberLabelsEnabled( layer->
customProperty( u
"labeling/limitNumLabels"_s, QVariant(
false ) ).toBool() );
1022 mThinningSettings.setMaximumNumberLabels( layer->
customProperty( u
"labeling/maxNumLabels"_s, QVariant( 2000 ) ).toInt() );
1023 mObstacleSettings.setIsObstacle( layer->
customProperty( u
"labeling/obstacle"_s, QVariant(
true ) ).toBool() );
1024 mObstacleSettings.setFactor( layer->
customProperty( u
"labeling/obstacleFactor"_s, QVariant( 1.0 ) ).toDouble() );
1025 mObstacleSettings.setType(
1032 mDataDefinedProperties.clear();
1033 if ( layer->
customProperty( u
"labeling/ddProperties"_s ).isValid() )
1035 QDomDocument doc( u
"dd"_s );
1036 doc.setContent( layer->
customProperty( u
"labeling/ddProperties"_s ).toString() );
1037 QDomElement elem = doc.firstChildElement( u
"properties"_s );
1038 mDataDefinedProperties.readXml( elem, *sPropertyDefinitions() );
1043 readOldDataDefinedPropertyMap( layer,
nullptr );
1048 mDataDefinedProperties
1054 mDataDefinedProperties
1060 mDataDefinedProperties
1066 mDataDefinedProperties
1072 mDataDefinedProperties
1092 QDomElement textStyleElem = elem.firstChildElement( u
"text-style"_s );
1093 fieldName = textStyleElem.attribute( u
"fieldName"_s );
1094 isExpression = textStyleElem.attribute( u
"isExpression"_s ).toInt();
1096 mFormat.readXml( elem, context );
1098 previewBkgrdColor = QColor( textStyleElem.attribute( u
"previewBkgrdColor"_s, u
"#ffffff"_s ) );
1100 substitutions.readXml( textStyleElem.firstChildElement( u
"substitutions"_s ) );
1101 useSubstitutions = textStyleElem.attribute( u
"useSubstitutions"_s ).toInt();
1102 mLegendString = textStyleElem.attribute( u
"legendString"_s, QObject::tr(
"Aa" ) );
1105 QDomElement textFormatElem = elem.firstChildElement( u
"text-format"_s );
1106 wrapChar = textFormatElem.attribute( u
"wrapChar"_s );
1107 autoWrapLength = textFormatElem.attribute( u
"autoWrapLength"_s, u
"0"_s ).toInt();
1112 mLineSettings.setAddDirectionSymbol( textFormatElem.attribute( u
"addDirectionSymbol"_s ).toInt() );
1113 mLineSettings.setLeftDirectionSymbol( textFormatElem.attribute( u
"leftDirectionSymbol"_s, u
"<"_s ) );
1114 mLineSettings.setRightDirectionSymbol( textFormatElem.attribute( u
"rightDirectionSymbol"_s, u
">"_s ) );
1115 mLineSettings.setReverseDirectionSymbol( textFormatElem.attribute( u
"reverseDirectionSymbol"_s ).toInt() );
1116 mLineSettings.setDirectionSymbolPlacement(
1121 formatNumbers = textFormatElem.attribute( u
"formatNumbers"_s ).toInt();
1122 decimals = textFormatElem.attribute( u
"decimals"_s ).toInt();
1123 plusSign = textFormatElem.attribute( u
"plussign"_s ).toInt();
1126 QDomElement placementElem = elem.firstChildElement( u
"placement"_s );
1133 centroidWhole = placementElem.attribute( u
"centroidWhole"_s, u
"0"_s ).toInt();
1134 centroidInside = placementElem.attribute( u
"centroidInside"_s, u
"0"_s ).toInt();
1137 if ( predefinedPositionOrder.isEmpty() )
1138 predefinedPositionOrder = *DEFAULT_PLACEMENT_ORDER();
1139 mPointSettings.setPredefinedPositionOrder( predefinedPositionOrder );
1141 fitInPolygonOnly = placementElem.attribute( u
"fitInPolygonOnly"_s, u
"0"_s ).toInt();
1142 dist = placementElem.attribute( u
"dist"_s ).toDouble();
1143 if ( !placementElem.hasAttribute( u
"distUnits"_s ) )
1145 if ( placementElem.attribute( u
"distInMapUnits"_s ).toInt() )
1154 if ( !placementElem.hasAttribute( u
"distMapUnitScale"_s ) )
1157 double oldMin = placementElem.attribute( u
"distMapUnitMinScale"_s, u
"0"_s ).toDouble();
1159 double oldMax = placementElem.attribute( u
"distMapUnitMaxScale"_s, u
"0"_s ).toDouble();
1167 mPointSettings.setQuadrant(
1170 xOffset = placementElem.attribute( u
"xOffset"_s, u
"0"_s ).toDouble();
1171 yOffset = placementElem.attribute( u
"yOffset"_s, u
"0"_s ).toDouble();
1172 if ( !placementElem.hasAttribute( u
"offsetUnits"_s ) )
1180 if ( !placementElem.hasAttribute( u
"labelOffsetMapUnitScale"_s ) )
1183 double oldMin = placementElem.attribute( u
"labelOffsetMapUnitMinScale"_s, u
"0"_s ).toDouble();
1185 double oldMax = placementElem.attribute( u
"labelOffsetMapUnitMaxScale"_s, u
"0"_s ).toDouble();
1193 if ( placementElem.hasAttribute( u
"angleOffset"_s ) )
1195 double oldAngle = placementElem.attribute( u
"angleOffset"_s, u
"0"_s ).toDouble();
1200 angleOffset = placementElem.attribute( u
"rotationAngle"_s, u
"0"_s ).toDouble();
1203 preserveRotation = placementElem.attribute( u
"preserveRotation"_s, u
"1"_s ).toInt();
1206 if ( rotationUnitString.startsWith(
"Angle"_L1 ) )
1209 rotationUnitString = rotationUnitString.mid( 5 );
1214 maxCurvedCharAngleIn = placementElem.attribute( u
"maxCurvedCharAngleIn"_s, u
"25"_s ).toDouble();
1216 priority = placementElem.attribute( u
"priority"_s ).toInt();
1217 repeatDistance = placementElem.attribute( u
"repeatDistance"_s, u
"0"_s ).toDouble();
1218 if ( !placementElem.hasAttribute( u
"repeatDistanceUnits"_s ) )
1221 switch ( placementElem.attribute( u
"repeatDistanceUnit"_s, QString::number( 1 ) ).toUInt() )
1241 if ( !placementElem.hasAttribute( u
"repeatDistanceMapUnitScale"_s ) )
1244 double oldMin = placementElem.attribute( u
"repeatDistanceMapUnitMinScale"_s, u
"0"_s ).toDouble();
1246 double oldMax = placementElem.attribute( u
"repeatDistanceMapUnitMaxScale"_s, u
"0"_s ).toDouble();
1254 mLineSettings.setOverrunDistance( placementElem.attribute( u
"overrunDistance"_s, u
"0"_s ).toDouble() );
1257 mLineSettings.setLineAnchorPercent( placementElem.attribute( u
"lineAnchorPercent"_s, u
"0.5"_s ).toDouble() );
1264 mPointSettings.setMaximumDistance( placementElem.attribute( u
"maximumDistance"_s, u
"0"_s ).toDouble() );
1271 QString geometryTypeKey = placementElem.attribute( u
"geometryGeneratorType"_s );
1273 if ( geometryTypeKey.endsWith(
"Geometry"_L1 ) )
1274 geometryTypeKey.chop( 8 );
1279 QString layerTypeKey = placementElem.attribute( u
"layerType"_s );
1281 if ( layerTypeKey.endsWith(
"Geometry"_L1 ) )
1282 layerTypeKey.chop( 8 );
1287 mPlacementSettings.setAllowDegradedPlacement( placementElem.attribute( u
"allowDegraded"_s, u
"0"_s ).toInt() );
1290 QDomElement renderingElem = elem.firstChildElement( u
"rendering"_s );
1292 drawLabels = renderingElem.attribute( u
"drawLabels"_s, u
"1"_s ).toInt();
1294 maximumScale = renderingElem.attribute( u
"scaleMin"_s, u
"0"_s ).toDouble();
1295 minimumScale = renderingElem.attribute( u
"scaleMax"_s, u
"0"_s ).toDouble();
1296 scaleVisibility = renderingElem.attribute( u
"scaleVisibility"_s ).toInt();
1298 fontLimitPixelSize = renderingElem.attribute( u
"fontLimitPixelSize"_s, u
"0"_s ).toInt();
1299 fontMinPixelSize = renderingElem.attribute( u
"fontMinPixelSize"_s, u
"0"_s ).toInt();
1300 fontMaxPixelSize = renderingElem.attribute( u
"fontMaxPixelSize"_s, u
"10000"_s ).toInt();
1302 if ( placementElem.hasAttribute( u
"overlapHandling"_s ) )
1309 if ( renderingElem.attribute( u
"displayAll"_s, u
"0"_s ).toInt() )
1312 mPlacementSettings.setAllowDegradedPlacement(
true );
1317 mPlacementSettings.setAllowDegradedPlacement(
false );
1327 if ( placementElem.hasAttribute( u
"multipartBehavior"_s ) )
1334 if ( renderingElem.attribute( u
"labelPerPart"_s, u
"0"_s ).toInt() )
1346 mLineSettings.setMergeLines( renderingElem.attribute( u
"mergeLines"_s ).toInt() );
1347 mThinningSettings.setMinimumFeatureSize( renderingElem.attribute( u
"minFeatureSize"_s ).toDouble() );
1348 mThinningSettings.setLimitNumberLabelsEnabled( renderingElem.attribute( u
"limitNumLabels"_s, u
"0"_s ).toInt() );
1349 mThinningSettings.setMaximumNumberLabels( renderingElem.attribute( u
"maxNumLabels"_s, u
"2000"_s ).toInt() );
1351 mThinningSettings.setLabelMarginDistance( placementElem.attribute( u
"labelMarginDistance"_s, u
"0"_s ).toDouble() );
1356 mThinningSettings.setMinimumDistanceToDuplicateUnit(
QgsUnitTypes::decodeRenderUnit( placementElem.attribute( u
"minDistanceToDuplicatesUnit"_s ) ) );
1358 mThinningSettings.setAllowDuplicateRemoval( placementElem.attribute( u
"allowDuplicateRemoval"_s, u
"0"_s ).toInt() );
1360 mObstacleSettings.setIsObstacle( renderingElem.attribute( u
"obstacle"_s, u
"1"_s ).toInt() );
1361 mObstacleSettings.setFactor( renderingElem.attribute( u
"obstacleFactor"_s, u
"1"_s ).toDouble() );
1362 mObstacleSettings.setType(
1367 zIndex = renderingElem.attribute( u
"zIndex"_s, u
"0.0"_s ).toDouble();
1372 QDomElement ddElem = elem.firstChildElement( u
"dd_properties"_s );
1373 if ( !ddElem.isNull() )
1375 mDataDefinedProperties.readXml( ddElem, *sPropertyDefinitions() );
1380 mDataDefinedProperties.clear();
1381 QDomElement ddElem = elem.firstChildElement( u
"data-defined"_s );
1382 readOldDataDefinedPropertyMap(
nullptr, &ddElem );
1387 mDataDefinedProperties
1393 mDataDefinedProperties
1399 mDataDefinedProperties
1405 mDataDefinedProperties
1411 mDataDefinedProperties
1428 const QString calloutType = elem.attribute( u
"calloutType"_s );
1429 if ( calloutType.isEmpty() )
1441 QDomElement textStyleElem = mFormat.writeXml( doc, context );
1444 textStyleElem.setAttribute( u
"fieldName"_s,
fieldName );
1445 textStyleElem.setAttribute( u
"isExpression"_s,
isExpression );
1446 QDomElement replacementElem = doc.createElement( u
"substitutions"_s );
1448 textStyleElem.appendChild( replacementElem );
1450 textStyleElem.setAttribute( u
"legendString"_s, mLegendString );
1453 QDomElement textFormatElem = doc.createElement( u
"text-format"_s );
1454 textFormatElem.setAttribute( u
"wrapChar"_s,
wrapChar );
1455 textFormatElem.setAttribute( u
"autoWrapLength"_s,
autoWrapLength );
1457 textFormatElem.setAttribute( u
"multilineAlign"_s,
static_cast< unsigned int >(
multilineAlign ) );
1458 textFormatElem.setAttribute( u
"addDirectionSymbol"_s, mLineSettings.addDirectionSymbol() );
1459 textFormatElem.setAttribute( u
"leftDirectionSymbol"_s, mLineSettings.leftDirectionSymbol() );
1460 textFormatElem.setAttribute( u
"rightDirectionSymbol"_s, mLineSettings.rightDirectionSymbol() );
1461 textFormatElem.setAttribute( u
"reverseDirectionSymbol"_s, mLineSettings.reverseDirectionSymbol() );
1462 textFormatElem.setAttribute( u
"placeDirectionSymbol"_s,
static_cast< unsigned int >( mLineSettings.directionSymbolPlacement() ) );
1463 textFormatElem.setAttribute( u
"formatNumbers"_s,
formatNumbers );
1464 textFormatElem.setAttribute( u
"decimals"_s,
decimals );
1465 textFormatElem.setAttribute( u
"plussign"_s,
plusSign );
1468 QDomElement placementElem = doc.createElement( u
"placement"_s );
1469 placementElem.setAttribute( u
"placement"_s,
static_cast< int >(
placement ) );
1470 placementElem.setAttribute( u
"polygonPlacementFlags"_s,
static_cast< int >( mPolygonPlacementFlags ) );
1471 placementElem.setAttribute( u
"placementFlags"_s,
static_cast< unsigned int >( mLineSettings.placementFlags() ) );
1472 placementElem.setAttribute( u
"centroidWhole"_s,
centroidWhole );
1473 placementElem.setAttribute( u
"centroidInside"_s,
centroidInside );
1476 placementElem.setAttribute( u
"dist"_s,
dist );
1479 placementElem.setAttribute( u
"offsetType"_s,
static_cast< unsigned int >(
offsetType ) );
1480 placementElem.setAttribute( u
"quadOffset"_s,
static_cast< unsigned int >( mPointSettings.quadrant() ) );
1481 placementElem.setAttribute( u
"xOffset"_s,
xOffset );
1482 placementElem.setAttribute( u
"yOffset"_s,
yOffset );
1485 placementElem.setAttribute( u
"rotationAngle"_s,
angleOffset );
1489 const QString rotationUnitString = u
"Angle"_s +
qgsEnumValueToKey( mRotationUnit );
1490 placementElem.setAttribute( u
"rotationUnit"_s, rotationUnitString );
1494 placementElem.setAttribute( u
"priority"_s,
priority );
1495 placementElem.setAttribute( u
"repeatDistance"_s,
repeatDistance );
1498 placementElem.setAttribute( u
"overrunDistance"_s, mLineSettings.overrunDistance() );
1499 placementElem.setAttribute( u
"overrunDistanceUnit"_s,
QgsUnitTypes::encodeUnit( mLineSettings.overrunDistanceUnit() ) );
1501 placementElem.setAttribute( u
"lineAnchorPercent"_s, mLineSettings.lineAnchorPercent() );
1502 placementElem.setAttribute( u
"lineAnchorType"_s,
static_cast< int >( mLineSettings.anchorType() ) );
1503 placementElem.setAttribute( u
"lineAnchorClipping"_s,
static_cast< int >( mLineSettings.anchorClipping() ) );
1504 placementElem.setAttribute( u
"lineAnchorTextPoint"_s,
qgsEnumValueToKey( mLineSettings.anchorTextPoint() ) );
1507 placementElem.setAttribute( u
"curvedLabelMode"_s,
qgsEnumValueToKey( mLineSettings.curvedLabelMode() ) );
1510 placementElem.setAttribute( u
"maximumDistance"_s, mPointSettings.maximumDistance() );
1511 placementElem.setAttribute( u
"maximumDistanceUnit"_s,
QgsUnitTypes::encodeUnit( mPointSettings.maximumDistanceUnit() ) );
1520 placementElem.setAttribute( u
"overlapHandling"_s,
qgsEnumValueToKey( mPlacementSettings.overlapHandling() ) );
1521 placementElem.setAttribute( u
"prioritization"_s,
qgsEnumValueToKey( mPlacementSettings.prioritization() ) );
1522 placementElem.setAttribute( u
"allowDegraded"_s, mPlacementSettings.allowDegradedPlacement() ? u
"1"_s : u
"0"_s );
1525 QDomElement renderingElem = doc.createElement( u
"rendering"_s );
1526 renderingElem.setAttribute( u
"drawLabels"_s,
drawLabels );
1528 renderingElem.setAttribute( u
"scaleMin"_s,
maximumScale );
1529 renderingElem.setAttribute( u
"scaleMax"_s,
minimumScale );
1533 renderingElem.setAttribute( u
"upsidedownLabels"_s,
static_cast< unsigned int >(
upsidedownLabels ) );
1534 placementElem.setAttribute( u
"multipartBehavior"_s,
qgsEnumValueToKey( mPlacementSettings.multiPartBehavior() ) );
1536 placementElem.setAttribute( u
"whitespaceCollisions"_s,
qgsEnumValueToKey( mPlacementSettings.whitespaceCollisionHandling() ) );
1537 renderingElem.setAttribute( u
"mergeLines"_s, mLineSettings.mergeLines() );
1538 renderingElem.setAttribute( u
"minFeatureSize"_s, mThinningSettings.minimumFeatureSize() );
1539 renderingElem.setAttribute( u
"limitNumLabels"_s, mThinningSettings.limitNumberOfLabelsEnabled() );
1540 renderingElem.setAttribute( u
"maxNumLabels"_s, mThinningSettings.maximumNumberLabels() );
1542 if ( mThinningSettings.labelMarginDistance() > 0 )
1544 placementElem.setAttribute( u
"labelMarginDistance"_s, mThinningSettings.labelMarginDistance() );
1548 placementElem.setAttribute( u
"labelMarginDistanceUnit"_s,
QgsUnitTypes::encodeUnit( mThinningSettings.labelMarginDistanceUnit() ) );
1550 if ( !mThinningSettings.labelMarginDistanceMapUnitScale().isNull() )
1557 placementElem.setAttribute( u
"minDistanceToDuplicates"_s, mThinningSettings.minimumDistanceToDuplicate() );
1561 placementElem.setAttribute( u
"minDistanceToDuplicatesUnit"_s,
QgsUnitTypes::encodeUnit( mThinningSettings.minimumDistanceToDuplicateUnit() ) );
1563 if ( !mThinningSettings.minimumDistanceToDuplicateMapUnitScale().isNull() )
1567 if ( mThinningSettings.allowDuplicateRemoval() )
1569 placementElem.setAttribute( u
"allowDuplicateRemoval"_s, u
"1"_s );
1572 renderingElem.setAttribute( u
"obstacle"_s, mObstacleSettings.isObstacle() );
1573 renderingElem.setAttribute( u
"obstacleFactor"_s, mObstacleSettings.factor() );
1574 renderingElem.setAttribute( u
"obstacleType"_s,
static_cast< unsigned int >( mObstacleSettings.type() ) );
1575 renderingElem.setAttribute( u
"zIndex"_s,
zIndex );
1576 renderingElem.setAttribute( u
"unplacedVisibility"_s,
static_cast< int >( mUnplacedVisibility ) );
1578 QDomElement ddElem = doc.createElement( u
"dd_properties"_s );
1579 mDataDefinedProperties.writeXml( ddElem, *sPropertyDefinitions() );
1581 QDomElement elem = doc.createElement( u
"settings"_s );
1582 elem.appendChild( textStyleElem );
1583 elem.appendChild( textFormatElem );
1584 elem.appendChild( placementElem );
1585 elem.appendChild( renderingElem );
1586 elem.appendChild( ddElem );
1590 elem.setAttribute( u
"calloutType"_s, mCallout->type() );
1591 mCallout->saveProperties( doc, elem, context );
1608 QPixmap pixmap( size * devicePixelRatio );
1609 pixmap.fill( Qt::transparent );
1610 pixmap.setDevicePixelRatio( devicePixelRatio );
1612 painter.begin( &pixmap );
1614 painter.setRenderHint( QPainter::Antialiasing );
1616 const QRectF rect( 0, 0, size.width(), size.height() );
1619 painter.setPen( Qt::NoPen );
1621 if ( ( background1.lightnessF() < 0.7 ) )
1623 background1 = background1.darker( 125 );
1627 background1 = background1.lighter( 125 );
1630 QLinearGradient linearGrad( QPointF( 0, 0 ), QPointF( 0, rect.height() ) );
1631 linearGrad.setColorAt( 0, background1 );
1632 linearGrad.setColorAt( 1, background2 );
1633 painter.setBrush( QBrush( linearGrad ) );
1634 if ( size.width() > 30 )
1636 painter.drawRoundedRect( rect, 6, 6 );
1641 painter.drawRect( rect );
1643 painter.setBrush( Qt::NoBrush );
1644 painter.setPen( Qt::NoPen );
1659 QWidget *activeWindow = QApplication::activeWindow();
1660 if ( QScreen *screen = activeWindow ? activeWindow->screen() :
nullptr )
1680 ? fontSize * tempFormat.
buffer().
size() / 100
1685 double ytrans = 0.0;
1695 const QStringList text = QStringList() << ( previewText.isEmpty() ? settings.
legendString() : previewText );
1697 QRectF textRect = rect;
1698 textRect.setLeft( xtrans + padding );
1699 textRect.setWidth( rect.width() - xtrans - 2 * padding );
1701 if ( textRect.width() > 2000 )
1702 textRect.setWidth( 2000 - 2 * padding );
1704 const double bottom = textRect.height() / 2 + textHeight / 2;
1705 textRect.setTop( bottom - textHeight );
1706 textRect.setBottom( bottom );
1715 callout->startRender( context );
1717 QRectF labelRect( textRect.left() + ( textRect.width() - textWidth ) / 2.0, textRect.top(), textWidth, textRect.height() );
1719 callout->stopRender( context );
1724 if ( size.width() > 30 )
1728 QgsApplication::getThemeIcon( u
"labelingSingle.svg"_s ).paint( &painter, QRect( rect.width() - iconWidth * 3, rect.height() - iconWidth * 3, iconWidth * 2, iconWidth * 2 ), Qt::AlignRight | Qt::AlignBottom );
1732 painter.setBrush( Qt::NoBrush );
1734 if ( size.width() > 30 )
1736 painter.drawRoundedRect( rect, 6, 6 );
1741 painter.drawRect( rect );
1750 return mUnplacedVisibility;
1755 mUnplacedVisibility = visibility;
1760 return QgsPalLabeling::checkMinimumSizeMM(
ct, geom, minSize );
1764 const QFontMetricsF *fm,
const QString &text,
double &labelX,
double &labelY,
const QgsFeature *f,
QgsRenderContext *context,
double *rotatedLabelX,
double *rotatedLabelY
1774 QString textCopy( text );
1777 std::unique_ptr< QgsRenderContext > scopedRc;
1780 scopedRc = std::make_unique<QgsRenderContext>();
1782 scopedRc->expressionContext().setFeature( *f );
1788 double multilineH = mFormat.lineHeight();
1791 bool addDirSymb = mLineSettings.addDirectionSymbol();
1792 QString leftDirSymb = mLineSettings.leftDirectionSymbol();
1793 QString rightDirSymb = mLineSettings.rightDirectionSymbol();
1897 if ( wrapchr.isEmpty() )
1905 QString dirSym = leftDirSymb;
1907 if ( fm->horizontalAdvance( rightDirSymb ) > fm->horizontalAdvance( dirSym ) )
1908 dirSym = rightDirSymb;
1910 switch ( placeDirSymb )
1913 textCopy.append( dirSym );
1918 textCopy.prepend( dirSym + u
"\n"_s );
1923 double w = 0.0, h = 0.0, rw = 0.0, rh = 0.0;
1924 double labelHeight = fm->ascent() + fm->descent();
1927 const int lines = multiLineSplit.size();
1929 const double lineHeightPainterUnits = rc->
convertToPainterUnits( mFormat.lineHeight(), mFormat.lineHeightUnit() );
1931 switch ( orientation )
1935 h += fm->height() +
static_cast< double >( ( lines - 1 ) * ( mFormat.lineHeightUnit() ==
Qgis::RenderUnit::Percentage ? ( labelHeight * multilineH ) : lineHeightPainterUnits ) );
1937 for (
const QString &line : std::as_const( multiLineSplit ) )
1939 w = std::max( w, fm->horizontalAdvance( line ) );
1946 double letterSpacing = mFormat.scaledFont( *rc ).letterSpacing();
1947 double labelWidth = fm->maxWidth();
1948 w = labelWidth + ( lines - 1 ) * ( mFormat.lineHeightUnit() ==
Qgis::RenderUnit::Percentage ? ( labelWidth * multilineH ) : lineHeightPainterUnits );
1950 int maxLineLength = 0;
1951 for (
const QString &line : std::as_const( multiLineSplit ) )
1953 maxLineLength = std::max( maxLineLength,
static_cast<int>( line.length() ) );
1955 h = fm->ascent() * maxLineLength + ( maxLineLength - 1 ) * letterSpacing;
1961 double widthHorizontal = 0.0;
1962 for (
const QString &line : std::as_const( multiLineSplit ) )
1964 widthHorizontal = std::max( widthHorizontal, fm->horizontalAdvance( line ) );
1967 double widthVertical = 0.0;
1968 double letterSpacing = mFormat.scaledFont( *rc ).letterSpacing();
1969 double labelWidth = fm->maxWidth();
1970 widthVertical = labelWidth + ( lines - 1 ) * ( mFormat.lineHeightUnit() ==
Qgis::RenderUnit::Percentage ? ( labelWidth * multilineH ) : lineHeightPainterUnits );
1972 double heightHorizontal = 0.0;
1973 heightHorizontal += fm->height() +
static_cast< double >( ( lines - 1 ) * ( mFormat.lineHeightUnit() ==
Qgis::RenderUnit::Percentage ? ( labelHeight * multilineH ) : lineHeightPainterUnits ) );
1975 double heightVertical = 0.0;
1976 int maxLineLength = 0;
1977 for (
const QString &line : std::as_const( multiLineSplit ) )
1979 maxLineLength = std::max( maxLineLength,
static_cast<int>( line.length() ) );
1981 heightVertical = fm->ascent() * maxLineLength + ( maxLineLength - 1 ) * letterSpacing;
1983 w = widthHorizontal;
1984 rw = heightVertical;
1985 h = heightHorizontal;
1991 double uPP =
xform->mapUnitsPerPixel();
1994 if ( rotatedLabelX && rotatedLabelY )
1996 *rotatedLabelX = rw * uPP;
1997 *rotatedLabelY = rh * uPP;
2001void QgsPalLayerSettings::calculateLabelMetrics(
2012 bool addDirSymb = mLineSettings.addDirectionSymbol();
2013 QString leftDirSymb = mLineSettings.leftDirectionSymbol();
2014 QString rightDirSymb = mLineSettings.rightDirectionSymbol();
2016 double multilineH = mFormat.lineHeight();
2050 const double lineHeightPainterUnits = context.
convertToPainterUnits( mFormat.lineHeight(), mFormat.lineHeightUnit() );
2053 QSizeF maximumExtraSpaceAllowance( 0, 0 );
2054 QSizeF minimumSize( 0, 0 );
2059 const QString dirSym = fm.horizontalAdvance( rightDirSymb ) > fm.horizontalAdvance( leftDirSymb ) ? rightDirSymb : leftDirSymb;
2061 switch ( placeDirSymb )
2064 maximumExtraSpaceAllowance = QSizeF( fm.horizontalAdvance( dirSym ), 0 );
2069 maximumExtraSpaceAllowance = QSizeF( 0, ( mFormat.lineHeightUnit() ==
Qgis::RenderUnit::Percentage ? ( ( fm.ascent() + fm.descent() ) * multilineH ) : lineHeightPainterUnits ) );
2070 minimumSize = QSizeF( fm.horizontalAdvance( dirSym ), 0 );
2082 w = std::max( minimumSize.width(), documentSize.width() + maximumExtraSpaceAllowance.width() );
2083 h = std::max( minimumSize.height(), documentSize.height() + maximumExtraSpaceAllowance.height() );
2088 rh = std::max( minimumSize.width(), rotatedSize.width() + maximumExtraSpaceAllowance.width() );
2089 rw = std::max( minimumSize.height(), rotatedSize.height() + maximumExtraSpaceAllowance.height() );
2092 const double uPP =
xform->mapUnitsPerPixel();
2093 size = QSizeF( w * uPP, h * uPP );
2094 rotatedSize = QSizeF( rw * uPP, rh * uPP );
2100 outerBounds = QRectF( outerBoundsPixels.left() * uPP, outerBoundsPixels.top() * uPP, outerBoundsPixels.width() * uPP, outerBoundsPixels.height() * uPP );
2125 if ( useScaleVisibility )
2138 maxScale = 1 / std::fabs( maxScale );
2158 minScale = 1 / std::fabs( minScale );
2173 labelIsHidden =
false;
2174 QgsTextFormat evaluatedFormat = mFormat;
2176 QFont labelFont = evaluatedFormat.
font();
2184 QString units = exprVal.toString();
2185 if ( !units.isEmpty() )
2195 double fontSize = evaluatedFormat.
size();
2201 if ( fontSize <= 0.0 )
2203 labelIsHidden =
true;
2204 return evaluatedFormat;
2209 if ( fontPixelSize < 1 )
2211 labelIsHidden =
true;
2212 return evaluatedFormat;
2214 labelFont.setPixelSize( fontPixelSize );
2226 if ( fontMinPixel > labelFont.pixelSize() || labelFont.pixelSize() > fontMaxPixel )
2228 labelIsHidden =
true;
2229 return evaluatedFormat;
2245 labelFont.setCapitalization( QFont::MixedCase );
2265 const QString fcase = exprVal.toString();
2266 auto evaluatedCase = FONT_CASE_MAP.lookup( fcase );
2267 if ( evaluatedCase )
2274 parseTextStyle( labelFont, fontunits, context );
2275 if ( mDataDefinedProperties.hasActiveProperties() )
2277 parseTextFormatting( context );
2278 parseTextBuffer( context );
2279 parseTextMask( context );
2280 parseShapeBackground( context );
2281 parseDropShadow( context );
2286 QList<QgsTextFormat::Tab> tabPositions;
2290 for (
const QVariant &part : parts )
2292 tabPositions.append( QgsTextFormat::Tab( part.toDouble() ) );
2299 for (
const QString &part : parts )
2301 tabPositions.append( QgsTextFormat::Tab( part.toDouble() ) );
2312 evaluatedFormat.
setFont( labelFont );
2316 evaluatedFormat.
setSize( labelFont.pixelSize() / symbologyReferenceScaleFactor );
2319 return evaluatedFormat;
2324 QgsTextFormat formatEvaluated =
format;
2367 if ( evalFormatNumbers )
2371 if ( decimalPlaces <= 0 )
2377 QVariant textV( labelText );
2379 double d = textV.toDouble( &ok );
2382 QString numberFormat;
2383 if ( d > 0 && signPlus )
2385 numberFormat.append(
'+' );
2387 numberFormat.append(
"%1" );
2388 labelText = numberFormat.arg( QLocale().toString( d,
'f', decimalPlaces ) );
2401 if ( allowMultipleLines )
2412 wrapchrCopy = wrapchr;
2414 if ( wrapchr.isEmpty() )
2417 wrapchrCopy = wrapchr;
2422 while ( labelText.contains( wrapchr ) )
2424 labelText.replace( wrapchr, QString( QChar::ReplacementCharacter ) );
2427 wrapchr = QString( QChar::ReplacementCharacter );
2432 labelText = document.
toPlainText().join( wrapchrCopy );
2434 if ( allowMultipleLines )
2444 QgsGeometry geom = feature.
geometry();
2451 bool allowSimplify =
true;
2461 allowSimplify =
false;
2482 std::unique_ptr<QgsGeometry> scopedClonedGeom;
2487 QgsMapToPixelSimplifier simplifier( simplifyHints, simplifyMethod.
tolerance(), simplifyAlgorithm );
2488 geom = simplifier.
simplify( geom );
2500 bool isObstacle = mObstacleSettings.isObstacle();
2504 std::vector<std::unique_ptr<QgsLabelFeature> > res;
2513 std::unique_ptr< QgsLabelFeature > obstacle = registerObstacleFeature( f, context, obstacleGeometry );
2515 res.emplace_back( std::move( obstacle ) );
2524 if ( !isLabelVisible( context ) )
2531 if ( mGeometryGeneratorExpression.hasEvalError() )
2534 if ( obstacleGeometry.
isNull() )
2547 dataDefinedValues.clear();
2550 bool labelIsHidden =
false;
2551 QgsTextFormat evaluatedFormat = evaluateTextFormat( context, labelIsHidden );
2552 if ( labelIsHidden )
2568 bool allowMultipleLines =
true;
2579 allowMultipleLines =
false;
2584 allowMultipleLines =
true;
2601 if ( !evaluateLabelContent( feature, context, allowMultipleLines, labelText, doc, evaluatedFormat ) )
2623 QString str = exprVal.toString().trimmed();
2626 if ( !str.isEmpty() )
2628 if ( str.compare(
"Visible"_L1, Qt::CaseInsensitive ) == 0 )
2630 wholeCentroid =
false;
2632 else if ( str.compare(
"Whole"_L1, Qt::CaseInsensitive ) == 0 )
2634 wholeCentroid =
true;
2645 bool doClip =
false;
2646 if ( !centroidPoly || !wholeCentroid )
2664 std::unique_ptr< QgsTextLabelFeature > label
2665 = generateLabelFeature( context, feature, 0, geom, obstacleGeometry, doc, labelText, evaluatedFormat, details.
symbol(),
lineSettings,
pointSettings,
placementSettings, isObstacle, doClip );
2667 res.emplace_back( std::move( label ) );
2675 const std::size_t partCount = std::min( geometryParts.size(), documentParts.size() );
2676 res.reserve( partCount );
2677 for ( std::size_t i = 0; i < partCount; ++i )
2679 std::unique_ptr< QgsTextLabelFeature > label
2680 = generateLabelFeature( context, feature,
static_cast< int >( i ), geometryParts[i], obstacleGeometry, documentParts[i], labelText, evaluatedFormat, details.
symbol(),
lineSettings,
pointSettings,
placementSettings, isObstacle, doClip );
2682 res.emplace_back( std::move( label ) );
2692std::unique_ptr< QgsTextLabelFeature> QgsPalLayerSettings::generateLabelFeature(
2699 const QString &labelText,
2715 QFontMetricsF labelFontMetrics( evaluatedFormat.
font() );
2716 calculateLabelMetrics( labelFontMetrics, context, evaluatedFormat, doc, documentMetrics, labelSize, rotatedSize, outerBounds );
2720 double maxcharanglein = 20.0;
2721 double maxcharangleout = -20.0;
2739 maxcharanglein = std::clamp(
static_cast< double >( maxcharanglePt.x() ), 20.0, 60.0 );
2740 maxcharangleout = std::clamp(
static_cast< double >( maxcharanglePt.y() ), 20.0, 95.0 );
2744 maxcharangleout = -( std::fabs( maxcharangleout ) );
2771 if ( dataDefinedOutside.userType() == QMetaType::Type::QString )
2773 const QString value = dataDefinedOutside.toString().trimmed();
2774 if ( value.compare(
"force"_L1, Qt::CaseInsensitive ) == 0 )
2780 else if ( value.compare(
"yes"_L1, Qt::CaseInsensitive ) == 0 )
2785 else if ( value.compare(
"no"_L1, Qt::CaseInsensitive ) == 0 )
2793 if ( dataDefinedOutside.toBool() )
2839 QgsGeometry permissibleZone;
2842 permissibleZone = geom;
2866 QgsLabelThinningSettings featureThinningSettings = mThinningSettings;
2869 double minimumSize = 0.0;
2879 if ( !checkMinimumSizeMM( context, geom, featureThinningSettings.
minimumFeatureSize() ) )
2884 if ( !geos_geom_clone )
2913 bool layerDefinedRotation =
false;
2914 bool dataDefinedRotation =
false;
2915 double xPos = 0.0, yPos = 0.0;
2916 double angleInRadians = 0.0;
2917 double quadOffsetX = 0.0, quadOffsetY = 0.0;
2918 double offsetX = 0.0, offsetY = 0.0;
2919 QgsPointXY anchorPosition;
2930 bool ddFixedQuad =
false;
2939 int quadInt = exprVal.toInt( &ok );
2940 if ( ok && 0 <= quadInt && quadInt <= 8 )
3010 QString units = exprVal.toString().trimmed();
3011 if ( !units.isEmpty() )
3017 offUnit = decodedUnits;
3032 layerDefinedRotation =
true;
3033 angleInRadians = ( 360 -
angleOffset ) * M_PI / 180;
3036 const QgsMapToPixel &m2p = context.
mapToPixel();
3045 const double rotation = exprVal.toDouble( &ok );
3048 dataDefinedRotation =
true;
3055 angleInRadians = ( 360 - rotationDegrees ) * M_PI / 180.0;
3060 bool hasDataDefinedPosition =
false;
3062 bool ddPosition =
false;
3072 bool ddXPos =
false, ddYPos =
false;
3073 xPos = xPosProperty.toDouble( &ddXPos );
3074 yPos = yPosProperty.toDouble( &ddYPos );
3075 if ( ddXPos && ddYPos )
3076 hasDataDefinedPosition =
true;
3087 if ( pointPosProperty.userType() == qMetaTypeId<QgsReferencedGeometry>() )
3089 QgsReferencedGeometry referencedGeometryPoint = pointPosProperty.value<QgsReferencedGeometry>();
3090 point = QgsPoint( referencedGeometryPoint.
asPoint() );
3092 if ( !referencedGeometryPoint.
isNull() &&
ct.sourceCrs() != referencedGeometryPoint.
crs() )
3094 QObject::tr(
"Label position geometry is not in layer coordinates reference system. Layer CRS: '%1', Geometry CRS: '%2'" )
3096 QObject::tr(
"Labeling" ),
3100 else if ( pointPosProperty.userType() == qMetaTypeId< QgsGeometry>() )
3102 point = QgsPoint( pointPosProperty.value<QgsGeometry>().asPoint() );
3107 hasDataDefinedPosition =
true;
3118 if ( hasDataDefinedPosition )
3121 if ( layerDefinedRotation && !dataDefinedRotation )
3123 angleInRadians = 0.0;
3132 QString haliString = exprVal.toString();
3133 if ( haliString.compare(
"Center"_L1, Qt::CaseInsensitive ) == 0 )
3135 xdiff -= labelSize.width() / 2.0;
3137 else if ( haliString.compare(
"Right"_L1, Qt::CaseInsensitive ) == 0 )
3139 xdiff -= labelSize.width();
3150 QString valiString = exprVal.toString();
3151 if ( valiString.compare(
"Bottom"_L1, Qt::CaseInsensitive ) != 0 )
3153 if ( valiString.compare(
"Top"_L1, Qt::CaseInsensitive ) == 0 )
3155 ydiff -= labelSize.height();
3159 double descentRatio = labelFontMetrics.descent() / labelFontMetrics.height();
3160 if ( valiString.compare(
"Base"_L1, Qt::CaseInsensitive ) == 0 )
3162 ydiff -= labelSize.height() * descentRatio;
3166 double capHeightRatio = ( labelFontMetrics.boundingRect(
'H' ).height() + 1 + labelFontMetrics.descent() ) / labelFontMetrics.height();
3167 ydiff -= labelSize.height() * capHeightRatio;
3168 if ( valiString.compare(
"Half"_L1, Qt::CaseInsensitive ) == 0 )
3170 ydiff += labelSize.height() * ( capHeightRatio - descentRatio ) / 2.0;
3178 if ( dataDefinedRotation )
3181 double xd = xdiff * std::cos( angleInRadians ) - ydiff * std::sin( angleInRadians );
3182 double yd = xdiff * std::sin( angleInRadians ) + ydiff * std::cos( angleInRadians );
3188 QgsGeometry ddPoint(
new QgsPoint( xPos, yPos ) );
3196 anchorPosition = QgsPointXY( xPos, yPos );
3200 QgsMessageLog::logMessage( QObject::tr(
"Invalid data defined label position (%1, %2)" ).arg( xPos ).arg( yPos ), QObject::tr(
"Labeling" ) );
3201 hasDataDefinedPosition =
false;
3206 anchorPosition = QgsPointXY( xPos, yPos );
3214 anchorPosition = QgsPointXY( xPos, yPos );
3220 bool alwaysShow =
false;
3242 QString units = exprVal.toString().trimmed();
3243 if ( !units.isEmpty() )
3249 repeatUnits = decodedUnits;
3264 double overrunDistanceEval =
lineSettings.overrunDistance();
3276 double maximumDistanceEval =
pointSettings.maximumDistance();
3283 auto labelFeature = std::make_unique< QgsTextLabelFeature>( feature.
id(), std::move( geos_geom_clone ), labelSize, subPartId );
3284 labelFeature->setAnchorPosition( anchorPosition );
3285 labelFeature->setFeature( feature );
3286 labelFeature->setSymbol( symbol );
3287 labelFeature->setDocument( doc, documentMetrics );
3289 labelFeature->setRotatedSize( rotatedSize );
3292 labelFeature->setHasFixedPosition( hasDataDefinedPosition );
3293 labelFeature->setFixedPosition( QgsPointXY( xPos, yPos ) );
3295 labelFeature->setHasFixedAngle( dataDefinedRotation || ( !hasDataDefinedPosition && !
qgsDoubleNear( angleInRadians, 0.0 ) ) );
3296 labelFeature->setFixedAngle( angleInRadians );
3297 labelFeature->setQuadOffset( QPointF( quadOffsetX, quadOffsetY ) );
3298 labelFeature->setPositionOffset( QgsPointXY( offsetX, offsetY ) );
3300 labelFeature->setAlwaysShow( alwaysShow );
3301 labelFeature->setRepeatDistance( repeatDist );
3302 labelFeature->setLabelText( labelText );
3303 labelFeature->setPermissibleZone( permissibleZone );
3304 labelFeature->setOverrunDistance( overrunDistanceEval );
3305 labelFeature->setOverrunSmoothDistance( overrunSmoothDist );
3306 labelFeature->setMaximumDistance( maximumDistanceEval );
3307 labelFeature->setLineAnchorPercent(
lineSettings.lineAnchorPercent() );
3308 labelFeature->setLineAnchorType(
lineSettings.anchorType() );
3309 labelFeature->setLineAnchorTextPoint(
lineSettings.anchorTextPoint() );
3310 labelFeature->setCurvedLabelMode(
lineSettings.curvedLabelMode() );
3313 labelFeature->setMinimumSize( minimumSize );
3314 labelFeature->setWhitespaceCollisionHandling(
placementSettings.whitespaceCollisionHandling() );
3321 if ( outerBounds.left() != 0 || outerBounds.top() != 0 || !
qgsDoubleNear( outerBounds.width(), labelSize.width() ) || !
qgsDoubleNear( outerBounds.height(), labelSize.height() ) )
3323 labelFeature->setOuterBounds( outerBounds );
3326 QgsLabelFeatureThinningSettings thinning;
3339 ( *labelFeature ).setThinningSettings( thinning );
3343 double topMargin = std::max( 0.25 * labelFontMetrics.ascent(), 0.0 );
3344 double bottomMargin = 1.0 + labelFontMetrics.descent();
3345 QgsMargins vm( 0.0, topMargin, 0.0, bottomMargin );
3346 vm *=
xform->mapUnitsPerPixel();
3347 labelFeature->setVisualMargin( vm );
3350 QgsDebugMsgLevel( u
"PAL font stored definedFont: %1, Style: %2"_s.arg( evaluatedFormat.
font().toString(), evaluatedFormat.
font().styleName() ), 4 );
3351 labelFeature->setDefinedFont( evaluatedFormat.
font() );
3353 labelFeature->setMaximumCharacterAngleInside( std::clamp( maxcharanglein, 20.0, 60.0 ) * M_PI / 180 );
3354 labelFeature->setMaximumCharacterAngleOutside( std::clamp( maxcharangleout, -95.0, -20.0 ) * M_PI / 180 );
3369 labelFeature->setTextMetrics(
3370 QgsTextLabelFeature::
3371 calculateTextMetrics(
xform, context, evaluatedFormat, evaluatedFormat.
font(), labelFontMetrics, evaluatedFormat.
font().letterSpacing(), evaluatedFormat.
font().wordSpacing(), doc, documentMetrics )
3381 double distance =
dist;
3395 QString units = exprVal.toString().trimmed();
3397 if ( !units.isEmpty() )
3403 distUnit = decodedUnits;
3417 distance = ( distance < 0 ? -1 : 1 ) * std::max( std::fabs( distance ), 1.0 );
3429 distance = std::max( distance, 2.0 );
3434 distance = std::max( distance, 2.0 );
3441 labelFeature->setDistLabel( d );
3446 labelFeature->setHasFixedQuadrant(
true );
3449 labelFeature->setArrangementFlags(
lineSettings.placementFlags() );
3451 labelFeature->setPolygonPlacementFlags( polygonPlacement );
3460 labelFeature->setZIndex( z );
3470 double priorityD = exprVal.toDouble( &ok );
3473 priorityD = std::clamp( priorityD, 0.0, 10.0 );
3474 priorityD = 1 - priorityD / 10.0;
3475 labelFeature->setPriority( priorityD );
3480 labelFeature->setAllowDegradedPlacement(
placementSettings.allowDegradedPlacement() );
3484 QgsLabelObstacleSettings os = mObstacleSettings;
3488 labelFeature->setObstacleSettings( os );
3490 QVector< Qgis::LabelPredefinedPointPosition > positionOrder =
pointSettings.predefinedPositionOrder();
3491 if ( positionOrder.isEmpty() )
3492 positionOrder = *DEFAULT_PLACEMENT_ORDER();
3498 if ( !dataDefinedOrder.isEmpty() )
3503 labelFeature->setPredefinedPositionOrder( positionOrder );
3506 labelFeature->setDataDefinedValues( dataDefinedValues );
3508 return labelFeature;
3516 if ( !obstacleGeometry.
isNull() )
3518 geom = obstacleGeometry;
3533 if ( ls->numPoints() < 2 )
3539 std::unique_ptr<QgsGeometry> scopedClonedGeom;
3544 QgsMapToPixelSimplifier simplifier( simplifyHints, simplifyMethod.
tolerance(), simplifyAlgorithm );
3545 geom = simplifier.
simplify( geom );
3549 std::unique_ptr<QgsGeometry> scopedPreparedGeom;
3557 if ( !geos_geom_clone )
3561 auto obstacleFeature = std::make_unique< QgsLabelFeature >( f.
id(), std::move( geos_geom_clone ), QSizeF( 0, 0 ) );
3562 obstacleFeature->setFeature( f );
3564 QgsLabelObstacleSettings os = mObstacleSettings;
3567 obstacleFeature->setObstacleSettings( os );
3570 return obstacleFeature;
3575 if ( !mDataDefinedProperties.isActive( p ) )
3579 exprVal = mDataDefinedProperties.value( p, context );
3586 bool bol = exprVal.toBool();
3587 dataDefinedValues.insert( p, QVariant( bol ) );
3593 int size = exprVal.toInt( &ok );
3597 dataDefinedValues.insert( p, QVariant( size ) );
3605 int size = exprVal.toInt( &ok );
3607 if ( ok && size > 0 )
3609 dataDefinedValues.insert( p, QVariant( size ) );
3617 double size = exprVal.toDouble( &ok );
3621 dataDefinedValues.insert( p, QVariant( size ) );
3629 double size = exprVal.toDouble( &ok );
3631 if ( ok && size > 0.0 )
3633 dataDefinedValues.insert( p, QVariant( size ) );
3641 double rot = exprVal.toDouble( &ok );
3644 if ( rot < -180.0 && rot >= -360 )
3648 if ( rot > 180.0 && rot <= 360 )
3652 if ( rot >= -180 && rot <= 180 )
3654 dataDefinedValues.insert( p, QVariant( rot ) );
3663 int size = exprVal.toInt( &ok );
3664 if ( ok && size >= 0 && size <= 100 )
3666 dataDefinedValues.insert( p, QVariant( size ) );
3673 QString str = exprVal.toString();
3675 dataDefinedValues.insert( p, QVariant( str ) );
3680 QString unitstr = exprVal.toString().trimmed();
3682 if ( !unitstr.isEmpty() )
3691 QString colorstr = exprVal.toString().trimmed();
3694 if ( color.isValid() )
3696 dataDefinedValues.insert( p, QVariant( color ) );
3703 QString joinstr = exprVal.toString().trimmed();
3705 if ( !joinstr.isEmpty() )
3714 QString blendstr = exprVal.toString().trimmed();
3716 if ( !blendstr.isEmpty() )
3729 dataDefinedValues.insert( p, res );
3740 dataDefinedValues.insert( p, res );
3761 QString ddFontFamily;
3768 QString family = exprVal.toString().trimmed();
3772 if ( labelFont.family() != family )
3778 ddFontFamily = family;
3785 QString ddFontStyle;
3791 QString fontstyle = exprVal.toString().trimmed();
3793 ddFontStyle = fontstyle;
3798 bool ddBold =
false;
3806 bool ddItalic =
false;
3816 QFont appFont = QApplication::font();
3817 bool newFontBuilt =
false;
3818 if ( ddBold || ddItalic )
3822 newFontBuilt =
true;
3823 newFont.setBold( ddBold );
3824 newFont.setItalic( ddItalic );
3826 else if ( !ddFontStyle.isEmpty() && ddFontStyle.compare(
"Ignore"_L1, Qt::CaseInsensitive ) != 0 )
3828 if ( !ddFontFamily.isEmpty() )
3832 mFontDB = std::make_unique< QFontDatabase >();
3834 QFont styledfont = mFontDB->font( ddFontFamily, ddFontStyle, appFont.pointSize() );
3835 if ( appFont != styledfont )
3837 newFont = styledfont;
3838 newFontBuilt =
true;
3845 else if ( !ddFontFamily.isEmpty() )
3847 if ( ddFontStyle.compare(
"Ignore"_L1, Qt::CaseInsensitive ) != 0 )
3851 mFontDB = std::make_unique< QFontDatabase >();
3852 QFont styledfont = mFontDB->font( ddFontFamily, mFormat.namedStyle(), appFont.pointSize() );
3853 if ( appFont != styledfont )
3855 newFont = styledfont;
3856 newFontBuilt =
true;
3862 newFontBuilt =
true;
3870 newFont.setPixelSize( labelFont.pixelSize() );
3871 newFont.setUnderline( labelFont.underline() );
3872 newFont.setStrikeOut( labelFont.strikeOut() );
3873 newFont.setWordSpacing( labelFont.wordSpacing() );
3874 newFont.setLetterSpacing( QFont::AbsoluteSpacing, labelFont.letterSpacing() );
3876 labelFont = newFont;
3880 double wordspace = labelFont.wordSpacing();
3886 labelFont.setWordSpacing( context.
convertToPainterUnits( wordspace, fontunits, mFormat.sizeMapUnitScale() ) );
3889 double letterspace = labelFont.letterSpacing();
3895 labelFont.setLetterSpacing( QFont::AbsoluteSpacing, context.
convertToPainterUnits( letterspace, fontunits, mFormat.sizeMapUnitScale() ) );
3902 labelFont.setStrikeOut( strikeout );
3917 labelFont.setUnderline( underline );
3936 QgsTextBufferSettings buffer = mFormat.buffer();
3939 bool drawBuffer = mFormat.buffer().enabled();
3942 drawBuffer = exprVal.toBool();
3955 double bufrSize = buffer.
size();
3958 bufrSize = exprVal.toDouble();
3962 double bufferOpacity = buffer.
opacity() * 100;
3965 bufferOpacity = exprVal.toDouble();
3968 drawBuffer = ( drawBuffer && bufrSize > 0.0 && bufferOpacity > 0 );
3995 QgsTextMaskSettings mask = mFormat.mask();
3998 bool maskEnabled = mask.
enabled();
4001 maskEnabled = exprVal.toBool();
4010 double bufrSize = mask.
size();
4013 bufrSize = exprVal.toDouble();
4017 double opacity = mask.
opacity() * 100;
4020 opacity = exprVal.toDouble();
4023 maskEnabled = ( maskEnabled && bufrSize > 0.0 && opacity > 0 );
4048 wrapchr = exprVal.toString();
4054 evalAutoWrapLength = exprVal.toInt();
4075 const QString str = exprVal.toString();
4086 auto evaluatedAlignment = MULTI_LINE_ALIGNMENT_MAP.lookup( str );
4087 if ( evaluatedAlignment )
4091 else if ( !str.isEmpty() )
4108 QString str = exprVal.toString().trimmed();
4109 if ( !str.isEmpty() )
4115 bool drawDirSymb = mLineSettings.addDirectionSymbol();
4118 drawDirSymb = exprVal.toBool();
4133 const QString str = exprVal.toString();
4141 auto evaluatedDirection = DIRECTION_MAP.lookup( str );
4142 if ( evaluatedDirection )
4146 else if ( !str.trimmed().isEmpty() )
4165 QgsTextBackgroundSettings background = mFormat.background();
4168 bool drawShape = background.
enabled();
4171 drawShape = exprVal.toBool();
4180 double shapeOpacity = background.
opacity() * 100;
4183 shapeOpacity = 100.0 * exprVal.toDouble();
4186 drawShape = ( drawShape && shapeOpacity > 0 );
4202 QString skind = exprVal.toString().trimmed();
4205 if ( !skind.isEmpty() )
4214 QString svgPath = background.
svgFile();
4221 QString svgfile = exprVal.toString().trimmed();
4237 QString stype = exprVal.toString().trimmed();
4240 if ( !stype.isEmpty() )
4249 double ddShpSizeX = background.
size().width();
4252 ddShpSizeX = exprVal.toDouble();
4256 double ddShpSizeY = background.
size().height();
4259 ddShpSizeY = exprVal.toDouble();
4276 && ( ddShpSizeX == 0.0 || ddShpSizeY == 0.0 ) )
4301 QString rotstr = exprVal.toString().trimmed();
4304 if ( !rotstr.isEmpty() )
4351 QgsTextShadowSettings shadow = mFormat.shadow();
4354 bool drawShadow = shadow.
enabled();
4357 drawShadow = exprVal.toBool();
4366 double shadowOpacity = shadow.
opacity() * 100;
4369 shadowOpacity = exprVal.toDouble();
4376 shadowOffDist = exprVal.toDouble();
4383 shadowRad = exprVal.toDouble();
4386 drawShadow = ( drawShadow && shadowOpacity > 0 && !( shadowOffDist == 0.0 && shadowRad == 0.0 ) );
4403 QString str = exprVal.toString().trimmed();
4406 if ( !str.isEmpty() )
4441 switch ( layer->
type() )
4445 const QgsVectorLayer *vl = qobject_cast< const QgsVectorLayer * >( layer );
4458 return !labeling->styles().empty();
4465 const QgsMeshLayer *ml = qobject_cast< const QgsMeshLayer * >( layer );
4471 const QgsRasterLayer *rl = qobject_cast< const QgsRasterLayer * >( layer );
4518QStringList
QgsPalLabeling::splitToLines(
const QString &text,
const QString &wrapCharacter,
const int autoWrapLength,
const bool useMaxLineLengthWhenAutoWrapping )
4520 QStringList multiLineSplit;
4521 if ( !wrapCharacter.isEmpty() && wrapCharacter !=
"\n"_L1 )
4524 const QStringList lines = text.split( wrapCharacter );
4525 for (
const QString &line : lines )
4527 multiLineSplit.append( line.split(
'\n' ) );
4532 multiLineSplit = text.split(
'\n' );
4536 if ( autoWrapLength != 0 )
4538 QStringList autoWrappedLines;
4539 autoWrappedLines.reserve( multiLineSplit.count() );
4540 for (
const QString &line : std::as_const( multiLineSplit ) )
4542 autoWrappedLines.append(
QgsStringUtils::wordWrap( line, autoWrapLength, useMaxLineLengthWhenAutoWrapping ).split(
'\n' ) );
4544 multiLineSplit = autoWrappedLines;
4546 return multiLineSplit;
4551 QStringList graphemes;
4552 QTextBoundaryFinder boundaryFinder( QTextBoundaryFinder::Grapheme, text );
4553 int currentBoundary = -1;
4554 int previousBoundary = 0;
4555 while ( ( currentBoundary = boundaryFinder.toNextBoundary() ) > 0 )
4557 graphemes << text.mid( previousBoundary, currentBoundary - previousBoundary );
4558 previousBoundary = currentBoundary;
4588 QgsDebugMsgLevel( u
"Ignoring feature due to transformation exception"_s, 4 );
4592 geom.
filterVertices( [](
const QgsPoint &point ) ->
bool {
return std::isfinite( point.
x() ) && std::isfinite( point.
y() ); } );
4595 cp->removeInvalidRings();
4599 for (
int i = 0; i < ms->numGeometries(); ++i )
4602 cp->removeInvalidRings();
4622 bool mustClipExact =
false;
4646 QVector< QgsGeometry> parts;
4655 parts.append( partGeom );
4662 if ( bufferGeom.
isNull() )
4671 if ( mustClipExact )
4706 double length = geom.
length();
4707 if ( length >= 0.0 )
4709 return ( length >= ( minSize * mapUnitsPerMM ) );
4714 double area = geom.
area();
4717 return ( std::sqrt( area ) >= ( minSize * mapUnitsPerMM ) );
4724void QgsPalLabeling::dataDefinedTextStyle(
QgsPalLayerSettings &tmpLyr,
const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
4726 QgsTextFormat format = tmpLyr.
format();
4727 bool changed =
false;
4733 format.
setColor( ddColor.value<QColor>() );
4757void QgsPalLabeling::dataDefinedTextFormatting(
QgsPalLayerSettings &tmpLyr,
const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
4771 QgsTextFormat format = tmpLyr.
format();
4778 QgsTextFormat format = tmpLyr.
format();
4779 QList<QgsTextFormat::Tab> tabPositions;
4783 for (
const QVariant &part : parts )
4785 tabPositions.append( QgsTextFormat::Tab( part.toDouble() ) );
4792 for (
const QString &part : parts )
4794 tabPositions.append( QgsTextFormat::Tab( part.toDouble() ) );
4813 QgsTextFormat format = tmpLyr.
format();
4846void QgsPalLabeling::dataDefinedTextBuffer(
QgsPalLayerSettings &tmpLyr,
const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
4848 QgsTextBufferSettings buffer = tmpLyr.
format().
buffer();
4849 bool changed =
false;
4862 QgsTextFormat format = tmpLyr.
format();
4897 buffer.
setColor( ddColor.value<QColor>() );
4917 QgsTextFormat format = tmpLyr.
format();
4923void QgsPalLabeling::dataDefinedTextMask(
QgsPalLayerSettings &tmpLyr,
const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
4925 if ( ddValues.isEmpty() )
4928 QgsTextMaskSettings mask = tmpLyr.
format().
mask();
4929 bool changed =
false;
4942 QgsTextFormat format = tmpLyr.
format();
4982 QgsTextFormat format = tmpLyr.
format();
4988void QgsPalLabeling::dataDefinedShapeBackground(
QgsPalLayerSettings &tmpLyr,
const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
4991 bool changed =
false;
5004 QgsTextFormat format = tmpLyr.
format();
5031 QSizeF size = background.
size();
5038 QSizeF size = background.
size();
5132 QgsTextFormat format = tmpLyr.
format();
5138void QgsPalLabeling::dataDefinedDropShadow(
QgsPalLayerSettings &tmpLyr,
const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
5140 QgsTextShadowSettings shadow = tmpLyr.
format().
shadow();
5141 bool changed =
false;
5154 QgsTextFormat format = tmpLyr.
format();
5200 shadow.
setColor( ddColor.value<QColor>() );
5225 QgsTextFormat format = tmpLyr.
format();
5235 QMimeData *mimeData =
new QMimeData;
5236 mimeData->setColorData( QVariant(
format().color() ) );
5239 QDomDocument textDoc;
5240 QDomElement textElem =
writeXml( textDoc, rwContext );
5241 textDoc.appendChild( textElem );
5242 mimeData->setData(
"application/qgis.labelsettings"_L1, textDoc.toString().toUtf8() );
5252 if ( !data || !data->hasFormat(
"application/qgis.labelsettings"_L1 ) )
5255 QString text = QString::fromUtf8( data->data(
"application/qgis.labelsettings"_L1 ) );
5256 if ( !text.isEmpty() )
5262 if ( doc.setContent( text ) )
5264 elem = doc.documentElement();
5266 settings.
readXml( elem, rwContext );
@ PreferVector
Prefer vector-based rendering, when the result will still be visually near-identical to a raster-base...
@ StretchCharacterSpacingToFitLine
Increases (or decreases) the character spacing used for each label in order to fit the entire text ov...
@ Default
Default curved placement, characters are placed in an optimal position along the line....
@ StretchWordSpacingToFitLine
Increases (or decreases) the word spacing used for each label in order to fit the entire text over th...
@ PlaceCharactersAtVertices
Each individual character from the label text is placed such that their left-baseline position is loc...
@ LabelLargestPartOnly
Place a label only on the largest part from the geometry.
@ SplitLabelTextLinesOverParts
Splits the label text over the parts of the geometry, such that each consecutive part is labeled with...
@ LabelEveryPartWithEntireLabel
Place the (same) entire label over every part from the geometry.
QFlags< VectorRenderingSimplificationFlag > VectorRenderingSimplificationFlags
Simplification flags for vector feature rendering.
@ Success
Operation succeeded.
AngleUnit
Units of angles.
@ NoSimplification
No simplification can be applied.
LabelOffsetType
Behavior modifier for label offset and distance, only applies in some label placement modes.
@ FromPoint
Offset distance applies from point geometry.
@ FromSymbolBounds
Offset distance applies from rendered symbol bounds.
@ PreferCloser
Prefer closer labels, falling back to alternate positions before larger distances.
LabelPlacement
Placement modes which determine how label candidates are generated for a feature.
@ OverPoint
Arranges candidates over a point (or centroid of a polygon), or at a preset offset from the point....
@ Curved
Arranges candidates following the curvature of a line feature. Applies to line layers only.
@ AroundPoint
Arranges candidates in a circle around a point (or centroid of a polygon). Applies to point or polygo...
@ Line
Arranges candidates parallel to a generalised line representing the feature or parallel to a polygon'...
@ Free
Arranges candidates scattered throughout a polygon feature. Candidates are rotated to respect the pol...
@ OrderedPositionsAroundPoint
Candidates are placed in predefined positions around a point. Preference is given to positions with g...
@ Horizontal
Arranges horizontal candidates scattered throughout a polygon feature or along a line feature....
@ PerimeterCurved
Arranges candidates following the curvature of a polygon's boundary. Applies to polygon layers only.
@ OutsidePolygons
Candidates are placed outside of polygon boundaries. Applies to polygon layers only.
@ AllowPlacementInsideOfPolygon
Labels can be placed inside a polygon feature.
@ AllowPlacementOutsideOfPolygon
Labels can be placed outside of a polygon feature.
VectorSimplificationAlgorithm
Simplification algorithms for vector features.
@ CenterOfText
Anchor using center of text.
@ SkipEmptyInteriorRings
Skip any empty polygon interior ring.
@ Warning
Warning message.
QFlags< LabelLinePlacementFlag > LabelLinePlacementFlags
Line placement flags, which control how candidates are generated for a linear feature.
@ Labeling
Labeling-specific layout mode.
@ Rectangle
Text within rectangle layout mode.
Capitalization
String capitalization options.
@ AllSmallCaps
Force all characters to small caps.
@ MixedCase
Mixed case, ie no change.
@ AllLowercase
Convert all characters to lowercase.
@ TitleCase
Simple title case conversion - does not fully grammatically parse the text and uses simple rules only...
@ SmallCaps
Mixed case small caps.
@ ForceFirstLetterToCapital
Convert just the first letter of each word to uppercase, leave the rest untouched.
@ AllUppercase
Convert all characters to uppercase.
QFlags< LabelPolygonPlacementFlag > LabelPolygonPlacementFlags
Polygon placement flags, which control how candidates are generated for a polygon feature.
LabelQuadrantPosition
Label quadrant positions.
TextOrientation
Text orientations.
@ Vertical
Vertically oriented text.
@ RotationBased
Horizontally or vertically oriented text based on rotation (only available for map labeling).
@ Horizontal
Horizontally oriented text.
UnplacedLabelVisibility
Unplaced label visibility.
@ FollowEngineSetting
Respect the label engine setting.
@ AffectsLabeling
If present, indicates that the renderer will participate in the map labeling problem.
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
LabelMultiLineAlignment
Text alignment for multi-line labels.
@ FollowPlacement
Alignment follows placement of label, e.g., labels to the left of a feature will be drawn with right ...
@ Group
Composite group layer. Added in QGIS 3.24.
@ Plugin
Plugin based layer.
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
@ Mesh
Mesh layer. Added in QGIS 3.2.
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
@ TreatWhitespaceAsCollision
Treat overlapping whitespace text in labels and whitespace overlapping obstacles as collisions.
RenderUnit
Rendering size units.
@ Percentage
Percentage of another measurement (e.g., canvas size, feature size).
@ Millimeters
Millimeters.
@ Points
Points (e.g., for font sizes).
@ DrawLabelSelection
Whether vector selections should be change the rendering of associated labels.
@ Antialiasing
Use antialiasing while drawing.
@ Linework
Combines all rings into a set of noded lines and then extracts valid polygons from that linework.
@ AllowOverlapIfRequired
Avoids overlapping labels when possible, but permit overlaps if labels for features cannot otherwise ...
@ PreventOverlap
Do not allow labels to overlap other labels.
static const double UI_SCALE_FACTOR
UI scaling factor.
@ MiddleLeft
Label on left of point.
@ TopRight
Label on top-right of point.
@ MiddleRight
Label on right of point.
@ TopSlightlyRight
Label on top of point, slightly right of center.
@ BottomRight
Label on bottom right of point.
@ BottomLeft
Label on bottom-left of point.
@ BottomSlightlyRight
Label below point, slightly right of center.
@ TopLeft
Label on top-left of point.
UpsideDownLabelHandling
Handling techniques for upside down labels.
@ FlipUpsideDownLabels
Upside-down labels (90 <= angle < 270) are shown upright.
virtual QgsAbstractGeometry * boundary() const =0
Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the...
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.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QgsFontManager * fontManager()
Returns the application font manager, which manages available fonts and font installation for the QGI...
static QgsCalloutRegistry * calloutRegistry()
Returns the application's callout registry, used for managing callout types.
Registry of available callout classes.
static std::unique_ptr< QgsCallout > defaultCallout()
Create a new instance of a callout with default settings.
std::unique_ptr< QgsCallout > createCallout(const QString &type, const QVariantMap &properties=QVariantMap(), const QgsReadWriteContext &context=QgsReadWriteContext()) const
Creates a new instance of a callout, given the callout type and properties.
Contains additional contextual information about the context in which a callout is being rendered.
Abstract base class for callout renderers.
bool enabled() const
Returns true if the callout is enabled.
static QColor colorFromString(const QString &string)
Decodes a string into a color value.
static QString colorToString(const QColor &color)
Encodes a color into a string value.
Represents a coordinate reference system (CRS).
QString userFriendlyIdentifier(Qgis::CrsIdentifierType type=Qgis::CrsIdentifierType::MediumString) const
Returns a user friendly identifier for the CRS.
Custom exception class for Coordinate Reference System related exceptions.
Curve polygon geometry type.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
QString evalErrorString() const
Returns evaluation error.
QString parserErrorString() const
Returns parser error.
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
QVariant evaluate()
Evaluate the feature and return the result.
virtual Qgis::FeatureRendererFlags flags() const
Returns flags associated with the renderer.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Container of fields for a vector layer.
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QString processFontFamilyName(const QString &name) const
Processes a font family name, applying any matching fontFamilyReplacements() to the name.
static QFont createFont(const QString &family, int pointSize=-1, int weight=-1, bool italic=false)
Creates a font with the specified family.
static bool fontFamilyOnSystem(const QString &family)
Check whether font family is on system in a quick manner, which does not compare [foundry].
static bool updateFontViaStyle(QFont &f, const QString &fontstyle, bool fallback=false)
Updates font with named style and retain all font properties.
Encapsulates parameters under which a geometry operation is performed.
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters ¶meters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing the points shared by this geometry and other.
double length() const
Returns the planar, 2-dimensional length of geometry.
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
static QgsGeometry collectGeometry(const QVector< QgsGeometry > &geometries)
Creates a new multipart geometry from a list of QgsGeometry objects.
QgsGeometry mergeLines(const QgsGeometryParameters ¶meters=QgsGeometryParameters()) const
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line ...
QString lastError() const
Returns an error string referring to the last error encountered either when this geometry was created...
QgsGeometry clipped(const QgsRectangle &rectangle, QgsFeedback *feedback=nullptr)
Clips the geometry using the specified rectangle.
bool isAxisParallelRectangle(double maximumDeviation, bool simpleRectanglesOnly=false) const
Returns true if the geometry is a polygon that is almost an axis-parallel rectangle.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool contains(const QgsPointXY *p) const
Returns true if the geometry contains the point p.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
void filterVertices(const std::function< bool(const QgsPoint &) > &filter)
Filters the vertices from the geometry in place, removing any which do not return true for the filter...
bool isGeosValid(Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const
Checks validity of the geometry using GEOS.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
double area() const
Returns the planar, 2-dimensional area of the geometry.
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
QgsGeometry makeValid(Qgis::MakeValidMethod method=Qgis::MakeValidMethod::Linework, bool keepCollapsed=false, QgsFeedback *feedback=nullptr) const
Attempts to make an invalid geometry valid without losing vertices.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
bool convertGeometryCollectionToSubclass(Qgis::GeometryType geomType)
Converts geometry collection to a the desired geometry type subclass (multi-point,...
QgsGeometry simplify(double tolerance, QgsFeedback *feedback=nullptr) const
Returns a simplified version of this geometry using a specified tolerance value.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::GeometryOperationResult rotate(double rotation, const QgsPointXY ¢er)
Rotate this geometry around the Z axis.
Q_INVOKABLE QString asWkt(int precision=17) const
Exports the geometry to WKT.
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlags())
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
Encapsulates details for an individual feature to label.
QgsGeometry obstacleGeometry() const
Returns the (optional) obstacle geometry for the label.
bool isSelected() const
Returns true if the feature associated with the label is currently selected.
const QgsSymbol * symbol() const
Returns the (optional) symbol associated with the feature to label.
void setNoRepeatDistance(double distance)
Sets the minimum distance (in label units) between labels for this feature and other labels with the ...
void setLabelMarginDistance(double distance)
Sets the minimum distance (in label units) between labels for this feature and other labels.
Contains settings related to how the label engine places and formats labels for line features (or pol...
AnchorType
Line anchor types.
AnchorClipping
Clipping behavior for line anchor calculation.
@ UseEntireLine
Entire original feature line geometry is used when calculating the line anchor for labels.
@ UseVisiblePartsOfLine
Only visible parts of lines are considered when calculating the line anchor for labels.
void setDirectionSymbolPlacement(DirectionSymbolPlacement placement)
Sets the placement for direction symbols.
void setLeftDirectionSymbol(const QString &symbol)
Sets the string to use for left direction arrows.
DirectionSymbolPlacement
Placement options for direction symbols.
@ SymbolLeftRight
Place direction symbols on left/right of label.
@ SymbolAbove
Place direction symbols on above label.
@ SymbolBelow
Place direction symbols on below label.
void setRightDirectionSymbol(const QString &symbol)
Sets the string to use for right direction arrows.
bool addDirectionSymbol() const
Returns true if '<' or '>' (or custom strings set via leftDirectionSymbol and rightDirectionSymbol) w...
void setReverseDirectionSymbol(bool reversed)
Sets whether the direction symbols should be reversed.
void setAddDirectionSymbol(bool enabled)
Sets whether '<' or '>' (or custom strings set via leftDirectionSymbol and rightDirectionSymbol) will...
ObstacleType
Valid obstacle types, which affect how features within the layer will act as obstacles for labels.
@ PolygonInterior
Avoid placing labels over interior of polygon (prefer placing labels totally outside or just slightly...
void setIsObstacle(bool isObstacle)
Sets whether features are obstacles to labels of other layers.
void updateDataDefinedProperties(const QgsPropertyCollection &properties, QgsExpressionContext &context)
Updates the obstacle settings to respect any data defined properties set within the specified propert...
void setObstacleGeometry(const QgsGeometry &obstacleGeom)
Sets the label's obstacle geometry, if different to the feature geometry.
Contains general settings related to how labels are placed.
Contains settings related to how the label engine places and formats labels for point-like features.
double minimumFeatureSize() const
Returns the minimum feature size (in millimeters) for a feature to be labelled.
const QgsMapUnitScale & minimumDistanceToDuplicateMapUnitScale() const
Returns the map unit scale for the minimum distance to labels with duplicate text.
int maximumNumberLabels() const
Returns the maximum number of labels which should be drawn for this layer.
bool allowDuplicateRemoval() const
Returns whether duplicate label removal is permitted for this layer.
const QgsMapUnitScale & labelMarginDistanceMapUnitScale() const
Returns the map unit scale for the minimum distance to other labels.
double labelMarginDistance() const
Returns the minimum distance to other labels (i.e.
Qgis::RenderUnit labelMarginDistanceUnit() const
Returns the units for the minimum distance to other labels.
void updateDataDefinedProperties(const QgsPropertyCollection &properties, QgsExpressionContext &context)
Updates the thinning settings to respect any data defined properties set within the specified propert...
double minimumDistanceToDuplicate() const
Returns the minimum distance to labels with duplicate text.
Qgis::RenderUnit minimumDistanceToDuplicateUnit() const
Returns the units for the minimum distance to labels with duplicate text.
bool limitNumberOfLabelsEnabled() const
Returns true if the number of labels drawn for the layer should be limited.
static constexpr double DEFAULT_MINIMUM_DISTANCE_TO_DUPLICATE
Default minimum distance to duplicate labels.
static QString encodePredefinedPositionOrder(const QVector< Qgis::LabelPredefinedPointPosition > &positions)
Encodes an ordered list of predefined point label positions to a string.
static QVector< Qgis::LabelPredefinedPointPosition > decodePredefinedPositionOrder(const QString &positionString)
Decodes a string to an ordered list of predefined point label positions.
Base class for all map layer types.
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
void removeCustomProperty(const QString &key)
Remove a custom property from layer.
T customEnumProperty(const QString &key, const T &defaultValue)
Returns the property value for a property based on an enum.
Contains configuration for rendering maps.
const QgsMapToPixel & mapToPixel() const
double extentBuffer() const
Returns the buffer in map units to use around the visible extent for rendering symbols whose correspo...
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes output image size into account.
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
@ SimplifyEnvelope
The geometries can be fully simplified by its BoundingBox.
Perform transforms between map coordinates and device coordinates.
double mapUnitsPerPixel() const
Returns the current map units per pixel.
double mapRotation() const
Returns the current map rotation in degrees (clockwise).
void setParameters(double mapUnitsPerPixel, double centerX, double centerY, int widthPixels, int heightPixels, double rotation)
Sets parameters for use in transforming coordinates.
Represents a mesh layer supporting display of data on structured or unstructured meshes.
const QgsAbstractMeshLayerLabeling * labeling() const
Access to const labeling configuration.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
Multi surface geometry collection.
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).
static QgsGeometry prepareGeometry(const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry=QgsGeometry(), bool mergeLines=false)
Prepares a geometry for registration with PAL.
static bool geometryRequiresPreparation(const QgsGeometry &geometry, QgsRenderContext &context, const QgsCoordinateTransform &ct, const QgsGeometry &clipGeometry=QgsGeometry(), bool mergeLines=false)
Checks whether a geometry requires preparation before registration with PAL.
static bool staticWillUseLayer(const QgsMapLayer *layer)
Called to find out whether a specified layer is used for labeling.
static QStringList splitToGraphemes(const QString &text)
Splits a text string to a list of graphemes, which are the smallest allowable character divisions in ...
Contains settings for how a map layer will be labeled.
bool fitInPolygonOnly
true if only labels which completely fit within a polygon are allowed.
double yOffset
Vertical offset of label.
QgsMapUnitScale labelOffsetMapUnitScale
Map unit scale for label offset.
int fontMaxPixelSize
Maximum pixel size for showing rendered map unit labels (1 - 10000).
const QgsLabelPlacementSettings & placementSettings() const
Returns the label placement settings.
double maxCurvedCharAngleIn
Maximum angle between inside curved label characters (valid range 20.0 to 60.0).
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...
const QgsMapToPixel * xform
void startRender(QgsRenderContext &context)
Prepares the label settings for rendering.
QString wrapChar
Wrapping character string.
QSet< QString > referencedFields(const QgsRenderContext &context) const
Returns all field names referenced by the configuration (e.g.
Qgis::LabelOffsetType offsetType
Offset type for layer (only applies in certain placement modes).
double xOffset
Horizontal offset of label.
Qgis::LabelPlacement placement
Label placement mode.
QgsCoordinateTransform ct
bool drawLabels
Whether to draw labels for this layer.
bool fontLimitPixelSize
true if label sizes should be limited by pixel size.
QString legendString() const
legendString
static QgsPalLayerSettings fromMimeData(const QMimeData *data, bool *ok=nullptr)
Attempts to parse the provided mime data as a QgsPalLayerSettings.
double minimumScale
The minimum map scale (i.e.
Q_DECL_DEPRECATED void calculateLabelSize(const QFontMetricsF *fm, const QString &text, double &labelX, double &labelY, const QgsFeature *f=nullptr, QgsRenderContext *context=nullptr, double *rotatedLabelX=nullptr, double *rotatedLabelY=nullptr)
Calculates the space required to render the provided text in map units.
void registerFeature(const QgsFeature &f, QgsRenderContext &context)
Registers a feature for labeling.
QgsPalLayerSettings & operator=(const QgsPalLayerSettings &s)
copy operator - only copies the permanent members
void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Read settings from a DOM element.
bool scaleVisibility
Set to true to limit label visibility to a range of scales.
double repeatDistance
Distance for repeating labels for a single feature.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label's property collection, used for data defined overrides.
QgsExpression * getLabelExpression() const
Returns the QgsExpression for this label settings.
bool geometryGeneratorEnabled
Defines if the geometry generator is enabled or not. If disabled, the standard geometry will be taken...
QMimeData * toMimeData() const
Returns new mime data representing the labeling settings.
Qgis::LabelMultiLineAlignment multilineAlign
Horizontal alignment of multi-line labels.
bool centroidInside
true if centroid positioned labels must be placed inside their corresponding feature polygon,...
int priority
Label priority.
Qgis::GeometryType geometryGeneratorType
The type of the result geometry of the geometry generator.
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Write settings into a DOM element.
QgsCallout * callout() const
Returns the label callout renderer, responsible for drawing label callouts.
int fontMinPixelSize
Minimum pixel size for showing rendered map unit labels (1 - 1000).
double angleOffset
Label rotation, in degrees clockwise.
double maxCurvedCharAngleOut
Maximum angle between outside curved label characters (valid range -20.0 to -95.0).
Qgis::AngleUnit rotationUnit() const
Unit for rotation of labels.
Qgis::GeometryType layerType
Geometry type of layers associated with these settings.
Qgis::RenderUnit offsetUnits
Units for offsets of label.
bool isExpression
true if this label is made from a expression string, e.g., FieldName || 'mm'
bool preserveRotation
True if label rotation should be preserved during label pin/unpin operations.
bool plusSign
Whether '+' signs should be prepended to positive numeric labels.
bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames, const QgsFields &fields, const QgsMapSettings &mapSettings, const QgsCoordinateReferenceSystem &crs)
Prepare for registration of features.
QString geometryGenerator
The geometry generator expression. Null if disabled.
const QgsLabelLineSettings & lineSettings() const
Returns the label line settings, which contain settings related to how the label engine places and fo...
QgsMapUnitScale distMapUnitScale
Map unit scale for label feature distance.
QgsStringReplacementCollection substitutions
Substitution collection for automatic text substitution with labels.
Q_DECL_DEPRECATED QColor previewBkgrdColor
const QgsFeature * mCurFeat
int decimals
Number of decimal places to show for numeric labels.
double dist
Distance from feature to the label.
void setRotationUnit(Qgis::AngleUnit angleUnit)
Set unit for rotation of labels.
QgsMapUnitScale repeatDistanceMapUnitScale
Map unit scale for repeating labels for a single feature.
Qgis::RenderUnit distUnits
Units the distance from feature to the label.
bool centroidWhole
true if feature centroid should be calculated from the whole feature, or false if only the visible pa...
Property
Data definable properties.
@ PositionX
X-coordinate data defined label position.
@ LinePlacementOptions
Line placement flags.
@ MinScale
Min scale (deprecated, for old project compatibility only).
@ FontSizeUnit
Font size units.
@ WhitespaceCollisionHandling
Whitespace collision handling.
@ LabelRotation
Label rotation.
@ FontStyle
Font style name.
@ ShapeTransparency
Shape transparency (deprecated).
@ Italic
Use italic style.
@ ShapeOpacity
Shape opacity.
@ AllowDegradedPlacement
Allow degraded label placements.
@ MaskEnabled
Whether the mask is enabled.
@ PredefinedPositionOrder
@ OverlapHandling
Overlap handling technique.
@ PositionY
Y-coordinate data defined label position.
@ MaximumScale
Maximum map scale (ie most "zoomed in").
@ Vali
Vertical alignment for data defined label position (Bottom, Base, Half, Cap, Top).
@ MinimumScale
Minimum map scale (ie most "zoomed out").
@ FontStretchFactor
Font stretch factor, since QGIS 3.24.
@ PolygonLabelOutside
Whether labels outside a polygon feature are permitted, or should be forced.
@ LineAnchorType
Line anchor type.
@ MaxScale
Max scale (deprecated, for old project compatibility only).
@ BufferOpacity
Buffer opacity.
@ BufferTransp
Buffer transparency (deprecated).
@ LineAnchorClipping
Clipping mode for line anchor calculation.
@ MaskJoinStyle
Mask join style.
@ Strikeout
Use strikeout.
@ LabelAllParts
Multipart geometry behavior.
@ LabelMarginDistance
Minimum distance from labels for this feature to other labels.
@ Underline
Use underline.
@ FontBlendMode
Text blend mode.
@ LineAnchorPercent
Portion along line at which labels should be anchored.
@ FontCase
Label text case.
@ Hali
Horizontal alignment for data defined label position (Left, Center, Right).
@ MaskOpacity
Mask opacity.
@ RemoveDuplicateLabelDistance
Minimum distance from labels for this feature to other labels with duplicate text.
@ LineAnchorTextPoint
Line anchor text point.
@ ShadowTransparency
Shadow transparency (deprecated).
@ OverrunDistance
Distance which labels can extend past either end of linear features.
@ MaskBufferUnit
Mask buffer size unit.
@ FontOpacity
Text opacity.
@ FontWordSpacing
Word spacing.
@ FontTransp
Text transparency (deprecated).
@ CalloutDraw
Show callout.
@ CurvedLabelMode
Mode which determine how curved labels are generated and placed.
@ MaskBufferSize
Mask buffer size.
@ FontLetterSpacing
Letter spacing.
@ TabStopDistance
Tab stop distance, since QGIS 3.38.
@ ShadowOpacity
Shadow opacity.
@ RemoveDuplicateLabels
Whether this feature can cause removal of duplicate labels.
@ PositionPoint
Point-coordinate data defined label position.
@ MaximumDistance
Maximum distance of label from feature.
@ Rotation
Label rotation (deprecated, for old project compatibility only).
Qgis::RenderUnit repeatDistanceUnit
Units for repeating labels for a single feature.
Qgis::UpsideDownLabelHandling upsidedownLabels
Controls whether upside down labels are displayed and how they are handled.
QString fieldName
Name of field (or an expression) to use for label text.
static QPixmap labelSettingsPreviewPixmap(const QgsPalLayerSettings &settings, QSize size, const QString &previewText=QString(), int padding=0, const QgsScreenProperties &screen=QgsScreenProperties())
Returns a pixmap preview for label settings.
bool formatNumbers
Set to true to format numeric label text as numbers (e.g.
bool containsAdvancedEffects() const
Returns true if any component of the label settings requires advanced effects such as blend modes,...
const QgsTextFormat & format() const
Returns the label text formatting settings, e.g., font settings, buffer settings, etc.
void setCallout(QgsCallout *callout)
Sets the label callout renderer, responsible for drawing label callouts.
double maximumScale
The maximum map scale (i.e.
int autoWrapLength
If non-zero, indicates that label text should be automatically wrapped to (ideally) the specified num...
Qgis::UnplacedLabelVisibility unplacedVisibility() const
Returns the layer's unplaced label visibility.
bool useMaxLineLengthForAutoWrap
If true, indicates that when auto wrapping label text the autoWrapLength length indicates the maximum...
void setUnplacedVisibility(Qgis::UnplacedLabelVisibility visibility)
Sets the layer's unplaced label visibility.
const QgsLabelPointSettings & pointSettings() const
Returns the label point settings, which contain settings related to how the label engine places and f...
static const QgsPropertiesDefinition & propertyDefinitions()
Returns the labeling property definitions.
void stopRender(QgsRenderContext &context)
Finalises the label settings after use.
std::vector< std::unique_ptr< QgsLabelFeature > > registerFeatureWithDetails(const QgsFeature &feature, QgsRenderContext &context, const QgsLabelFeatureDetails &details)
Registers a feature for labeling.
bool useSubstitutions
True if substitutions should be applied.
Point geometry type, with support for z-dimension and m-values.
QVariant value(int key, const QgsExpressionContext &context, const QVariant &defaultValue=QVariant()) const final
Returns the calculated value of the property with the specified key from within the collection.
bool isActive(int key) const final
Returns true if the collection contains an active property with the specified key.
@ Double
Double value (including negative values).
@ Double0To1
Double value between 0-1 (inclusive).
@ StrokeWidth
Line stroke width.
@ String
Any string value.
@ RenderUnits
Render units (eg mm/pixels/map units).
@ PenJoinStyle
Pen join style.
@ SvgPath
Path to an SVG file.
@ IntegerPositiveGreaterZero
Non-zero positive integer values.
@ IntegerPositive
Positive integer values (including 0).
@ Opacity
Opacity (0-100).
@ ColorNoAlpha
Color with no alpha channel.
@ Rotation
Rotation (value between 0-360 degrees).
@ ColorWithAlpha
Color with alpha channel.
@ DoublePositive
Positive double value (including 0).
@ Size2D
2D size (width/height different)
@ DataTypeString
Property requires a string value.
@ DataTypeNumeric
Property requires a numeric value.
A store for object properties.
static QgsProperty fromExpression(const QString &expression, bool isActive=true)
Returns a new ExpressionBasedProperty created from the specified expression.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
Represents a raster layer.
const QgsAbstractRasterLayerLabeling * labeling() const
Access to const labeling configuration.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
A container for the context for various read/write operations on objects.
A rectangle specified with double values.
Q_INVOKABLE QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be rounded to the spec...
bool contains(const QgsRectangle &rect) const
Returns true when rectangle contains other rectangle.
void grow(double delta)
Grows the rectangle in place by the specified amount.
QgsCoordinateReferenceSystem crs() const
Returns the associated coordinate reference system, or an invalid CRS if no reference system is set.
Contains information about the context of a rendering operation.
double scaleFactor() const
Returns the scaling factor for the render to convert painter units to physical sizes.
double convertToMapUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
void setScaleFactor(double factor)
Sets the scaling factor for the render to convert painter units to physical sizes.
QgsVectorSimplifyMethod & vectorSimplifyMethod()
Returns the simplification settings to use when rendering vector layers.
double symbologyReferenceScale() const
Returns the symbology reference scale.
void setDevicePixelRatio(float ratio)
Sets the device pixel ratio.
double convertToPainterUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale(), Qgis::RenderSubcomponentProperty property=Qgis::RenderSubcomponentProperty::Generic) const
Converts a size from the specified units to painter units (pixels).
double rendererScale() const
Returns the renderer map scale.
QgsExpressionContext & expressionContext()
Gets the expression context.
QgsGeometry featureClipGeometry() const
Returns the geometry to use to clip features at render time.
bool testFlag(Qgis::RenderContextFlag flag) const
Check whether a particular flag is enabled.
QgsRectangle mapExtent() const
Returns the original extent of the map being rendered.
void setRasterizedRenderingPolicy(Qgis::RasterizedRenderingPolicy policy)
Sets the policy controlling when rasterisation of content during renders is permitted.
void setFlag(Qgis::RenderContextFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QColor selectionColor() const
Returns the color to use when rendering selected features.
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly during rendering to check if rendering shou...
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
const QgsPathResolver & pathResolver() const
Returns the path resolver for conversion between relative and absolute paths during rendering operati...
static bool equalToOrGreaterThanMinimumScale(const double scale, const double minScale)
Returns whether the scale is equal to or greater than the minScale, taking non-round numbers into acc...
static bool lessThanMaximumScale(const double scale, const double maxScale)
Returns whether the scale is less than the maxScale, taking non-round numbers into account.
Stores properties relating to a screen.
double devicePixelRatio() const
Returns the ratio between physical pixels and device-independent pixels for the screen.
bool isValid() const
Returns true if the properties are valid.
void updateRenderContextForScreen(QgsRenderContext &context) const
Updates the settings in a render context to match the screen settings.
static QString wordWrap(const QString &string, int length, bool useMaxLineLength=true, const QString &customDelimiter=QString())
Automatically wraps a string by inserting new line characters at appropriate locations in the string.
QgsTextFormat defaultTextFormat(QgsStyle::TextFormatContext context=QgsStyle::TextFormatContext::Labeling) const
Returns the default text format to use for new text based objects in the specified context.
static QgsStyle * defaultStyle(bool initialize=true)
Returns the default application-wide style.
@ Labeling
Text format used in labeling.
static Qt::PenJoinStyle decodePenJoinStyle(const QString &str)
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
static QPointF toPoint(const QVariant &value, bool *ok=nullptr)
Converts a value to a point.
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
static QSizeF toSize(const QVariant &value, bool *ok=nullptr)
Converts a value to a size.
static QPainter::CompositionMode decodeBlendMode(const QString &s)
static QString encodeSize(QSizeF size)
Encodes a QSizeF to a string.
static QString svgSymbolNameToPath(const QString &name, const QgsPathResolver &pathResolver)
Determines an SVG symbol's path from its name.
static QString encodePoint(QPointF point)
Encodes a QPointF to a string.
static QString encodePenJoinStyle(Qt::PenJoinStyle style)
Abstract base class for all rendered symbols.
void setRadiiUnit(Qgis::RenderUnit units)
Sets the units used for the shape's radii.
QString svgFile() const
Returns the absolute path to the background SVG file, if set.
QSizeF size() const
Returns the size of the background shape.
QSizeF radii() const
Returns the radii used for rounding the corners of shapes.
void setOpacity(double opacity)
Sets the background shape's opacity.
void setStrokeColor(const QColor &color)
Sets the color used for outlining the background shape.
Qt::PenJoinStyle joinStyle() const
Returns the join style used for drawing the background shape.
SizeType
Methods for determining the background shape size.
bool enabled() const
Returns whether the background is enabled.
void setJoinStyle(Qt::PenJoinStyle style)
Sets the join style used for drawing the background shape.
double opacity() const
Returns the background shape's opacity.
double rotation() const
Returns the rotation for the background shape, in degrees clockwise.
QColor fillColor() const
Returns the color used for filing the background shape.
void setRadii(QSizeF radii)
Sets the radii used for rounding the corners of shapes.
SizeType sizeType() const
Returns the method used to determine the size of the background shape (e.g., fixed size or buffer aro...
ShapeType type() const
Returns the type of background shape (e.g., square, ellipse, SVG).
double strokeWidth() const
Returns the width of the shape's stroke (stroke).
void setSizeType(SizeType type)
Sets the method used to determine the size of the background shape (e.g., fixed size or buffer around...
ShapeType
Background shape types.
@ ShapeMarkerSymbol
Marker symbol.
void setFillColor(const QColor &color)
Sets the color used for filing the background shape.
void setSizeUnit(Qgis::RenderUnit unit)
Sets the units used for the shape's size.
QColor strokeColor() const
Returns the color used for outlining the background shape.
void setRotationType(RotationType type)
Sets the method used for rotating the background shape.
void setBlendMode(QPainter::CompositionMode mode)
Sets the blending mode used for drawing the background shape.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the shape size.
void setType(ShapeType type)
Sets the type of background shape to draw (e.g., square, ellipse, SVG).
Qgis::RenderUnit sizeUnit() const
Returns the units used for the shape's size.
RotationType
Methods for determining the rotation of the background shape.
void setEnabled(bool enabled)
Sets whether the text background will be drawn.
QgsMarkerSymbol * markerSymbol() const
Returns the marker symbol to be rendered in the background.
void setRotation(double rotation)
Sets the rotation for the background shape, in degrees clockwise.
void setStrokeWidthUnit(Qgis::RenderUnit units)
Sets the units used for the shape's stroke width.
void setOffsetUnit(Qgis::RenderUnit units)
Sets the units used for the shape's offset.
void setOffset(QPointF offset)
Sets the offset used for drawing the background shape.
void setSize(QSizeF size)
Sets the size of the background shape.
void setSvgFile(const QString &file)
Sets the path to the background SVG file.
void setStrokeWidth(double width)
Sets the width of the shape's stroke (stroke).
QPointF offset() const
Returns the offset used for drawing the background shape.
void setBlendMode(QPainter::CompositionMode mode)
Sets the blending mode used for drawing the buffer.
Qgis::RenderUnit sizeUnit() const
Returns the units for the buffer size.
Qt::PenJoinStyle joinStyle() const
Returns the buffer join style.
double size() const
Returns the size of the buffer.
void setColor(const QColor &color)
Sets the color for the buffer.
void setOpacity(double opacity)
Sets the buffer opacity.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the buffer size.
bool enabled() const
Returns whether the buffer is enabled.
double opacity() const
Returns the buffer opacity.
void setSizeUnit(Qgis::RenderUnit unit)
Sets the units used for the buffer size.
void setEnabled(bool enabled)
Sets whether the text buffer will be drawn.
QColor color() const
Returns the color of the buffer.
void setJoinStyle(Qt::PenJoinStyle style)
Sets the join style used for drawing the buffer.
void setSize(double size)
Sets the size of the buffer.
Contains pre-calculated metrics of a QgsTextDocument.
QSizeF documentSize(Qgis::TextLayoutMode mode, Qgis::TextOrientation orientation) const
Returns the overall size of the document.
static QgsTextDocumentMetrics calculateMetrics(const QgsTextDocument &document, const QgsTextFormat &format, const QgsRenderContext &context, double scaleFactor=1.0, const QgsTextDocumentRenderContext &documentContext=QgsTextDocumentRenderContext())
Returns precalculated text metrics for a text document, when rendered using the given base format and...
QRectF outerBounds(Qgis::TextLayoutMode mode, Qgis::TextOrientation orientation) const
Returns the outer bounds of the document, which is the documentSize() adjusted to account for any tex...
Represents a document consisting of one or more QgsTextBlock objects.
void splitLines(const QString &wrapCharacter, int autoWrapLength=0, bool useMaxLineLengthWhenAutoWrapping=true)
Splits lines of text in the document to separate lines, using a specified wrap character (wrapCharact...
QStringList toPlainText() const
Returns a list of plain text lines of text representing the document.
QVector< QgsTextDocument > splitBlocksToDocuments() const
Splits the text document, such that each block in the document becomes a separate document of its own...
static QgsTextDocument fromTextAndFormat(const QStringList &lines, const QgsTextFormat &format)
Constructor for QgsTextDocument consisting of a set of lines, respecting settings from a text format.
Container for all settings relating to text rendering.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
void setBlendMode(QPainter::CompositionMode mode)
Sets the blending mode used for drawing the text.
void setSize(double size)
Sets the size for rendered text.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the size.
void setCapitalization(Qgis::Capitalization capitalization)
Sets the text capitalization style.
void setOrientation(Qgis::TextOrientation orientation)
Sets the orientation for the text.
void setFont(const QFont &font)
Sets the font used for rendering text.
void setSizeUnit(Qgis::RenderUnit unit)
Sets the units for the size of rendered text.
void setShadow(const QgsTextShadowSettings &shadowSettings)
Sets the text's drop shadow settings.
void setMask(const QgsTextMaskSettings &maskSettings)
Sets the text's masking settings.
void setOpacity(double opacity)
Sets the text's opacity.
Qgis::Capitalization capitalization() const
Returns the text capitalization style.
QgsTextMaskSettings & mask()
Returns a reference to the masking settings.
void setBuffer(const QgsTextBufferSettings &bufferSettings)
Sets the text's buffer settings.
QgsTextBackgroundSettings & background()
Returns a reference to the text background settings.
Qgis::RenderUnit sizeUnit() const
Returns the units for the size of rendered text.
void setTabStopDistance(double distance)
Sets the distance for tab stops.
double size() const
Returns the size for rendered text.
QgsTextShadowSettings & shadow()
Returns a reference to the text drop shadow settings.
void setTabPositions(const QList< QgsTextFormat::Tab > &positions)
Sets the list of tab positions for tab stops.
void setBackground(const QgsTextBackgroundSettings &backgroundSettings)
Sets the text's background settings.q.
QFont font() const
Returns the font used for rendering text.
QColor previewBackgroundColor() const
Returns the background color for text previews.
QgsTextBufferSettings & buffer()
Returns a reference to the text buffer settings.
void setLineHeight(double height)
Sets the line height for text.
void setEnabled(bool)
Returns whether the mask is enabled.
void setSize(double size)
Sets the size of the buffer.
double size() const
Returns the size of the buffer.
void setJoinStyle(Qt::PenJoinStyle style)
Sets the join style used for drawing the buffer.
double opacity() const
Returns the mask's opacity.
bool enabled() const
Returns whether the mask is enabled.
void setSizeUnit(Qgis::RenderUnit unit)
Sets the units used for the buffer size.
Qt::PenJoinStyle joinStyle() const
Returns the buffer join style.
void setOpacity(double opacity)
Sets the mask's opacity.
static QgsTextBackgroundSettings::ShapeType decodeShapeType(const QString &string)
Decodes a string representation of a background shape type to a type.
static Qgis::TextOrientation decodeTextOrientation(const QString &name, bool *ok=nullptr)
Attempts to decode a string representation of a text orientation.
static QgsTextShadowSettings::ShadowPlacement decodeShadowPlacementType(const QString &string)
Decodes a string representation of a shadow placement type to a type.
static QgsTextBackgroundSettings::RotationType decodeBackgroundRotationType(const QString &string)
Decodes a string representation of a background rotation type to a type.
static QString encodeTextOrientation(Qgis::TextOrientation orientation)
Encodes a text orientation.
static QgsTextBackgroundSettings::SizeType decodeBackgroundSizeType(const QString &string)
Decodes a string representation of a background size type to a type.
static double textWidth(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, QFontMetricsF *fontMetrics=nullptr)
Returns the width of a text based on a given format.
static int sizeToPixel(double size, const QgsRenderContext &c, Qgis::RenderUnit unit, const QgsMapUnitScale &mapUnitScale=QgsMapUnitScale())
Calculates pixel size (considering output size should be in pixel or map units, scale factors and opt...
static void drawText(const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, bool drawAsOutlines=true, Qgis::TextVerticalAlignment vAlignment=Qgis::TextVerticalAlignment::Top, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Rectangle)
Draws text within a rectangle using the specified settings.
static double textHeight(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Point, QFontMetricsF *fontMetrics=nullptr, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), double maxLineWidth=0)
Returns the height of a text based on a given format.
int offsetAngle() const
Returns the angle for offsetting the position of the shadow from the text.
void setBlurRadiusUnit(Qgis::RenderUnit units)
Sets the units used for the shadow's blur radius.
bool enabled() const
Returns whether the shadow is enabled.
void setOffsetUnit(Qgis::RenderUnit units)
Sets the units used for the shadow's offset.
int scale() const
Returns the scaling used for the drop shadow (in percentage of original size).
void setShadowPlacement(QgsTextShadowSettings::ShadowPlacement placement)
Sets the placement for the drop shadow.
double opacity() const
Returns the shadow's opacity.
void setBlendMode(QPainter::CompositionMode mode)
Sets the blending mode used for drawing the drop shadow.
void setColor(const QColor &color)
Sets the color for the drop shadow.
QColor color() const
Returns the color of the drop shadow.
ShadowPlacement
Placement positions for text shadow.
void setScale(int scale)
Sets the scaling used for the drop shadow (in percentage of original size).
double offsetDistance() const
Returns the distance for offsetting the position of the shadow from the text.
void setOffsetDistance(double distance)
Sets the distance for offsetting the position of the shadow from the text.
void setOpacity(double opacity)
Sets the shadow's opacity.
void setOffsetAngle(int angle)
Sets the angle for offsetting the position of the shadow from the text.
double blurRadius() const
Returns the blur radius for the shadow.
void setBlurRadius(double blurRadius)
Sets the blur radius for the shadow.
void setEnabled(bool enabled)
Sets whether the text shadow will be drawn.
static Q_INVOKABLE double fromUnitToUnitFactor(Qgis::DistanceUnit fromUnit, Qgis::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
static Q_INVOKABLE Qgis::RenderUnit decodeRenderUnit(const QString &string, bool *ok=nullptr)
Decodes a render unit from a string.
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based dataset.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
bool diagramsEnabled() const
Returns whether the layer contains diagrams which are enabled and should be drawn.
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
QgsFeatureRenderer * renderer()
Returns the feature renderer used for rendering the features in the layer in 2D map views.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
const QgsDiagramRenderer * diagramRenderer() const
double tolerance() const
Gets the tolerance of simplification in map units. Represents the maximum distance in map units betwe...
bool forceLocalOptimization() const
Gets where the simplification executes, after fetch the geometries from provider, or when supported,...
Qgis::VectorRenderingSimplificationFlags simplifyHints() const
Gets the simplification hints of the vector layer managed.
Qgis::VectorSimplificationAlgorithm simplifyAlgorithm() const
Gets the local simplification algorithm of the vector layer managed.
Basic labeling configuration for vector tile layers.
Implements a map layer that is dedicated to rendering of vector tiles.
QgsVectorTileLabeling * labeling() const
Returns currently assigned labeling.
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
#define Q_NOWARN_DEPRECATED_POP
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
#define Q_NOWARN_DEPRECATED_PUSH
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
T qgsgeometry_cast(QgsAbstractGeometry *geom)
constexpr QgsDataDefinedStringDecoder< V, N > makeDataDefinedStringDecoder(const DataDefinedDecoderEntry< V >(&values)[N])
Creates a QgsDataDefinedStringDecoder from a hardcoded lookup table.
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
QString updateDataDefinedString(const QString &value)
QVector< Qgis::LabelPredefinedPointPosition > PredefinedPointPositionVector
Q_GLOBAL_STATIC_WITH_ARGS(PredefinedPointPositionVector, DEFAULT_PLACEMENT_ORDER,({ Qgis::LabelPredefinedPointPosition::TopRight, Qgis::LabelPredefinedPointPosition::TopLeft, Qgis::LabelPredefinedPointPosition::BottomRight, Qgis::LabelPredefinedPointPosition::BottomLeft, Qgis::LabelPredefinedPointPosition::MiddleRight, Qgis::LabelPredefinedPointPosition::MiddleLeft, Qgis::LabelPredefinedPointPosition::TopSlightlyRight, Qgis::LabelPredefinedPointPosition::BottomSlightlyRight })) void QgsPalLayerSettings
QMap< int, QgsPropertyDefinition > QgsPropertiesDefinition
Definition of available properties.