35 #include <QApplication> 38 #include <QFontMetrics> 41 #include <QDesktopWidget> 68 #include <QMessageBox> 102 void QgsPalLayerSettings::initPropertyDefinitions()
104 if ( !sPropertyDefinitions()->isEmpty() )
107 const QString origin = QStringLiteral(
"labeling" );
119 "e.g. Helvetica or Helvetica [Cronyx]" ), origin )
123 "e.g. Bold Condensed or Light Italic" ), origin )
163 "<b>Ellipse</b>|<b>Circle</b>|<b>SVG</b>]" ), origin )
187 "<b>Buffer</b>|<b>Background</b>]" ), origin )
203 "<b>3</b>=Left|<b>4</b>=Over|<b>5</b>=Right|<br>" 204 "<b>6</b>=Below Left|<b>7</b>=Below|<b>8</b>=Below Right]" ), origin )
220 + QStringLiteral(
"[<b>TL</b>=Top left|<b>TSL</b>=Top, slightly left|<b>T</b>=Top middle|<br>" 221 "<b>TSR</b>=Top, slightly right|<b>TR</b>=Top right|<br>" 222 "<b>L</b>=Left|<b>R</b>=Right|<br>" 223 "<b>BL</b>=Bottom left|<b>BSL</b>=Bottom, slightly left|<b>B</b>=Bottom middle|<br>" 224 "<b>BSR</b>=Bottom, slightly right|<b>BR</b>=Bottom right]" ), origin )
228 + QStringLiteral(
"[<b>OL</b>=On line|<b>AL</b>=Above line|<b>BL</b>=Below line|<br>" 229 "<b>LO</b>=Respect line orientation]" ), origin )
236 "<b>Half</b>|<b>Cap</b>|<b>Top</b>]" ), origin )
259 : predefinedPositionOrder( *DEFAULT_PLACEMENT_ORDER() )
262 initPropertyDefinitions();
269 , mDataDefinedProperties( s.mDataDefinedProperties )
350 mDataDefinedProperties = s.mDataDefinedProperties;
352 mCallout.reset( s.mCallout ? s.mCallout->clone() : nullptr );
354 mObstacleSettings = s.mObstacleSettings;
355 mThinningSettings = s.mThinningSettings;
410 for (
const QString &name : referencedColumns )
412 attributeNames.insert( name );
468 for (
const QString &name : referencedColumns )
470 attributeNames.insert( name );
476 const auto referencedColumns = mCallout->referencedFields( context );
477 for (
const QString &name : referencedColumns )
479 attributeNames.insert( name );
488 if ( mRenderStarted )
490 qWarning(
"Start render called for when a previous render was already underway!!" );
503 mCallout->startRender( context );
506 mRenderStarted =
true;
511 if ( !mRenderStarted )
513 qWarning(
"Stop render called for QgsPalLayerSettings without a startRender call!" );
519 mCallout->stopRender( context );
522 mRenderStarted =
false;
527 if ( mRenderStarted )
529 qWarning(
"stopRender was not called on QgsPalLayerSettings object!" );
540 initPropertyDefinitions();
541 return *sPropertyDefinitions();
556 QString newValue = value;
557 if ( !value.isEmpty() && !value.contains( QLatin1String(
"~~" ) ) )
560 values << QStringLiteral(
"1" );
561 values << QStringLiteral(
"0" );
564 newValue = values.join( QStringLiteral(
"~~" ) );
572 QString newPropertyName =
"labeling/dataDefined/" + sPropertyDefinitions()->value( p ).name();
573 QVariant newPropertyField = layer->
customProperty( newPropertyName, QVariant() );
575 if ( !newPropertyField.isValid() )
578 QString ddString = newPropertyField.toString();
580 if ( !ddString.isEmpty() && ddString != QLatin1String(
"0~~0~~~~" ) )
584 QStringList ddv = newStyleString.split( QStringLiteral(
"~~" ) );
586 bool active = ddv.at( 0 ).toInt();
587 if ( ddv.at( 1 ).toInt() )
603 void QgsPalLayerSettings::readOldDataDefinedPropertyMap(
QgsVectorLayer *layer, QDomElement *parentElem )
605 if ( !layer && !parentElem )
610 QgsPropertiesDefinition::const_iterator i = sPropertyDefinitions()->constBegin();
611 for ( ; i != sPropertyDefinitions()->constEnd(); ++i )
616 readOldDataDefinedProperty( layer, static_cast< Property >( i.key() ) );
618 else if ( parentElem )
621 QDomElement e = parentElem->firstChildElement( i.value().name() );
624 bool active = e.attribute( QStringLiteral(
"active" ) ).compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0;
625 bool isExpression = e.attribute( QStringLiteral(
"useExpr" ) ).compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0;
639 void QgsPalLayerSettings::readFromLayerCustomProperties(
QgsVectorLayer *layer )
641 if ( layer->
customProperty( QStringLiteral(
"labeling" ) ).toString() != QLatin1String(
"pal" ) )
666 QDomDocument doc( QStringLiteral(
"substitutions" ) );
667 doc.setContent( layer->
customProperty( QStringLiteral(
"labeling/substitutions" ) ).toString() );
668 QDomElement replacementElem = doc.firstChildElement( QStringLiteral(
"substitutions" ) );
698 if ( layer->
customProperty( QStringLiteral(
"labeling/distMapUnitScale" ) ).toString().isEmpty() )
701 double oldMin = layer->
customProperty( QStringLiteral(
"labeling/distMapUnitMinScale" ), 0.0 ).toDouble();
703 double oldMax = layer->
customProperty( QStringLiteral(
"labeling/distMapUnitMaxScale" ), 0.0 ).toDouble();
714 if ( layer->
customProperty( QStringLiteral(
"labeling/labelOffsetInMapUnits" ), QVariant(
true ) ).toBool() )
719 if ( layer->
customProperty( QStringLiteral(
"labeling/labelOffsetMapUnitScale" ) ).toString().isEmpty() )
722 double oldMin = layer->
customProperty( QStringLiteral(
"labeling/labelOffsetMapUnitMinScale" ), 0.0 ).toDouble();
724 double oldMax = layer->
customProperty( QStringLiteral(
"labeling/labelOffsetMapUnitMaxScale" ), 0.0 ).toDouble();
732 QVariant tempAngle = layer->
customProperty( QStringLiteral(
"labeling/angleOffset" ), QVariant() );
733 if ( tempAngle.isValid() )
735 double oldAngle = layer->
customProperty( QStringLiteral(
"labeling/angleOffset" ), QVariant( 0.0 ) ).toDouble();
748 switch ( layer->
customProperty( QStringLiteral(
"labeling/repeatDistanceUnit" ), QVariant( 1 ) ).toUInt() )
763 if ( layer->
customProperty( QStringLiteral(
"labeling/repeatDistanceMapUnitScale" ) ).toString().isEmpty() )
766 double oldMin = layer->
customProperty( QStringLiteral(
"labeling/repeatDistanceMapUnitMinScale" ), 0.0 ).toDouble();
768 double oldMax = layer->
customProperty( QStringLiteral(
"labeling/repeatDistanceMapUnitMaxScale" ), 0.0 ).toDouble();
777 double scalemn = layer->
customProperty( QStringLiteral(
"labeling/scaleMin" ), QVariant( 0 ) ).toDouble();
778 double scalemx = layer->
customProperty( QStringLiteral(
"labeling/scaleMax" ), QVariant( 0 ) ).toDouble();
781 QVariant scalevis = layer->
customProperty( QStringLiteral(
"labeling/scaleVisibility" ), QVariant() );
782 if ( scalevis.isValid() )
788 else if ( scalemn > 0 || scalemx > 0 )
813 mObstacleSettings.
setFactor( layer->
customProperty( QStringLiteral(
"labeling/obstacleFactor" ), QVariant( 1.0 ) ).toDouble() );
814 mObstacleSettings.
setType( static_cast< QgsLabelObstacleSettings::ObstacleType >( layer->
customProperty( QStringLiteral(
"labeling/obstacleType" ), QVariant(
PolygonInterior ) ).toUInt() ) );
815 zIndex = layer->
customProperty( QStringLiteral(
"labeling/zIndex" ), QVariant( 0.0 ) ).toDouble();
817 mDataDefinedProperties.
clear();
818 if ( layer->
customProperty( QStringLiteral(
"labeling/ddProperties" ) ).isValid() )
820 QDomDocument doc( QStringLiteral(
"dd" ) );
821 doc.setContent( layer->
customProperty( QStringLiteral(
"labeling/ddProperties" ) ).toString() );
822 QDomElement elem = doc.firstChildElement( QStringLiteral(
"properties" ) );
823 mDataDefinedProperties.
readXml( elem, *sPropertyDefinitions() );
828 readOldDataDefinedPropertyMap( layer,
nullptr );
872 QDomElement textStyleElem = elem.firstChildElement( QStringLiteral(
"text-style" ) );
873 fieldName = textStyleElem.attribute( QStringLiteral(
"fieldName" ) );
874 isExpression = textStyleElem.attribute( QStringLiteral(
"isExpression" ) ).toInt();
876 mFormat.
readXml( elem, context );
878 previewBkgrdColor = QColor( textStyleElem.attribute( QStringLiteral(
"previewBkgrdColor" ), QStringLiteral(
"#ffffff" ) ) );
881 useSubstitutions = textStyleElem.attribute( QStringLiteral(
"useSubstitutions" ) ).toInt();
884 QDomElement textFormatElem = elem.firstChildElement( QStringLiteral(
"text-format" ) );
885 wrapChar = textFormatElem.attribute( QStringLiteral(
"wrapChar" ) );
886 autoWrapLength = textFormatElem.attribute( QStringLiteral(
"autoWrapLength" ), QStringLiteral(
"0" ) ).toInt();
887 useMaxLineLengthForAutoWrap = textFormatElem.attribute( QStringLiteral(
"useMaxLineLengthForAutoWrap" ), QStringLiteral(
"1" ) ).toInt();
889 addDirectionSymbol = textFormatElem.attribute( QStringLiteral(
"addDirectionSymbol" ) ).toInt();
890 leftDirectionSymbol = textFormatElem.attribute( QStringLiteral(
"leftDirectionSymbol" ), QStringLiteral(
"<" ) );
891 rightDirectionSymbol = textFormatElem.attribute( QStringLiteral(
"rightDirectionSymbol" ), QStringLiteral(
">" ) );
894 formatNumbers = textFormatElem.attribute( QStringLiteral(
"formatNumbers" ) ).toInt();
895 decimals = textFormatElem.attribute( QStringLiteral(
"decimals" ) ).toInt();
896 plusSign = textFormatElem.attribute( QStringLiteral(
"plussign" ) ).toInt();
899 QDomElement placementElem = elem.firstChildElement( QStringLiteral(
"placement" ) );
900 placement =
static_cast< Placement >( placementElem.attribute( QStringLiteral(
"placement" ) ).toInt() );
901 placementFlags = placementElem.attribute( QStringLiteral(
"placementFlags" ) ).toUInt();
902 centroidWhole = placementElem.attribute( QStringLiteral(
"centroidWhole" ), QStringLiteral(
"0" ) ).toInt();
903 centroidInside = placementElem.attribute( QStringLiteral(
"centroidInside" ), QStringLiteral(
"0" ) ).toInt();
907 fitInPolygonOnly = placementElem.attribute( QStringLiteral(
"fitInPolygonOnly" ), QStringLiteral(
"0" ) ).toInt();
908 dist = placementElem.attribute( QStringLiteral(
"dist" ) ).toDouble();
909 if ( !placementElem.hasAttribute( QStringLiteral(
"distUnits" ) ) )
911 if ( placementElem.attribute( QStringLiteral(
"distInMapUnits" ) ).toInt() )
920 if ( !placementElem.hasAttribute( QStringLiteral(
"distMapUnitScale" ) ) )
923 double oldMin = placementElem.attribute( QStringLiteral(
"distMapUnitMinScale" ), QStringLiteral(
"0" ) ).toDouble();
925 double oldMax = placementElem.attribute( QStringLiteral(
"distMapUnitMaxScale" ), QStringLiteral(
"0" ) ).toDouble();
934 xOffset = placementElem.attribute( QStringLiteral(
"xOffset" ), QStringLiteral(
"0" ) ).toDouble();
935 yOffset = placementElem.attribute( QStringLiteral(
"yOffset" ), QStringLiteral(
"0" ) ).toDouble();
936 if ( !placementElem.hasAttribute( QStringLiteral(
"offsetUnits" ) ) )
944 if ( !placementElem.hasAttribute( QStringLiteral(
"labelOffsetMapUnitScale" ) ) )
947 double oldMin = placementElem.attribute( QStringLiteral(
"labelOffsetMapUnitMinScale" ), QStringLiteral(
"0" ) ).toDouble();
949 double oldMax = placementElem.attribute( QStringLiteral(
"labelOffsetMapUnitMaxScale" ), QStringLiteral(
"0" ) ).toDouble();
957 if ( placementElem.hasAttribute( QStringLiteral(
"angleOffset" ) ) )
959 double oldAngle = placementElem.attribute( QStringLiteral(
"angleOffset" ), QStringLiteral(
"0" ) ).toDouble();
964 angleOffset = placementElem.attribute( QStringLiteral(
"rotationAngle" ), QStringLiteral(
"0" ) ).toDouble();
967 preserveRotation = placementElem.attribute( QStringLiteral(
"preserveRotation" ), QStringLiteral(
"1" ) ).toInt();
968 maxCurvedCharAngleIn = placementElem.attribute( QStringLiteral(
"maxCurvedCharAngleIn" ), QStringLiteral(
"25" ) ).toDouble();
969 maxCurvedCharAngleOut = placementElem.attribute( QStringLiteral(
"maxCurvedCharAngleOut" ), QStringLiteral(
"-25" ) ).toDouble();
970 priority = placementElem.attribute( QStringLiteral(
"priority" ) ).toInt();
971 repeatDistance = placementElem.attribute( QStringLiteral(
"repeatDistance" ), QStringLiteral(
"0" ) ).toDouble();
972 if ( !placementElem.hasAttribute( QStringLiteral(
"repeatDistanceUnits" ) ) )
975 switch ( placementElem.attribute( QStringLiteral(
"repeatDistanceUnit" ), QString::number( 1 ) ).toUInt() )
995 if ( !placementElem.hasAttribute( QStringLiteral(
"repeatDistanceMapUnitScale" ) ) )
998 double oldMin = placementElem.attribute( QStringLiteral(
"repeatDistanceMapUnitMinScale" ), QStringLiteral(
"0" ) ).toDouble();
1000 double oldMax = placementElem.attribute( QStringLiteral(
"repeatDistanceMapUnitMaxScale" ), QStringLiteral(
"0" ) ).toDouble();
1008 overrunDistance = placementElem.attribute( QStringLiteral(
"overrunDistance" ), QStringLiteral(
"0" ) ).toDouble();
1012 geometryGenerator = placementElem.attribute( QStringLiteral(
"geometryGenerator" ) );
1019 QDomElement renderingElem = elem.firstChildElement( QStringLiteral(
"rendering" ) );
1021 drawLabels = renderingElem.attribute( QStringLiteral(
"drawLabels" ), QStringLiteral(
"1" ) ).toInt();
1023 maximumScale = renderingElem.attribute( QStringLiteral(
"scaleMin" ), QStringLiteral(
"0" ) ).toDouble();
1024 minimumScale = renderingElem.attribute( QStringLiteral(
"scaleMax" ), QStringLiteral(
"0" ) ).toDouble();
1025 scaleVisibility = renderingElem.attribute( QStringLiteral(
"scaleVisibility" ) ).toInt();
1027 fontLimitPixelSize = renderingElem.attribute( QStringLiteral(
"fontLimitPixelSize" ), QStringLiteral(
"0" ) ).toInt();
1028 fontMinPixelSize = renderingElem.attribute( QStringLiteral(
"fontMinPixelSize" ), QStringLiteral(
"0" ) ).toInt();
1029 fontMaxPixelSize = renderingElem.attribute( QStringLiteral(
"fontMaxPixelSize" ), QStringLiteral(
"10000" ) ).toInt();
1030 displayAll = renderingElem.attribute( QStringLiteral(
"displayAll" ), QStringLiteral(
"0" ) ).toInt();
1033 labelPerPart = renderingElem.attribute( QStringLiteral(
"labelPerPart" ) ).toInt();
1034 mergeLines = renderingElem.attribute( QStringLiteral(
"mergeLines" ) ).toInt();
1035 mThinningSettings.
setMinimumFeatureSize( renderingElem.attribute( QStringLiteral(
"minFeatureSize" ) ).toDouble() );
1036 mThinningSettings.
setLimitNumberLabelsEnabled( renderingElem.attribute( QStringLiteral(
"limitNumLabels" ), QStringLiteral(
"0" ) ).toInt() );
1037 mThinningSettings.
setMaximumNumberLabels( renderingElem.attribute( QStringLiteral(
"maxNumLabels" ), QStringLiteral(
"2000" ) ).toInt() );
1038 mObstacleSettings.
setIsObstacle( renderingElem.attribute( QStringLiteral(
"obstacle" ), QStringLiteral(
"1" ) ).toInt() );
1039 mObstacleSettings.
setFactor( renderingElem.attribute( QStringLiteral(
"obstacleFactor" ), QStringLiteral(
"1" ) ).toDouble() );
1040 mObstacleSettings.
setType( static_cast< QgsLabelObstacleSettings::ObstacleType >( renderingElem.attribute( QStringLiteral(
"obstacleType" ), QString::number(
PolygonInterior ) ).toUInt() ) );
1041 zIndex = renderingElem.attribute( QStringLiteral(
"zIndex" ), QStringLiteral(
"0.0" ) ).toDouble();
1043 QDomElement ddElem = elem.firstChildElement( QStringLiteral(
"dd_properties" ) );
1044 if ( !ddElem.isNull() )
1046 mDataDefinedProperties.
readXml( ddElem, *sPropertyDefinitions() );
1051 mDataDefinedProperties.
clear();
1052 QDomElement ddElem = elem.firstChildElement( QStringLiteral(
"data-defined" ) );
1053 readOldDataDefinedPropertyMap(
nullptr, &ddElem );
1094 const QString calloutType = elem.attribute( QStringLiteral(
"calloutType" ) );
1095 if ( calloutType.isEmpty() )
1107 QDomElement textStyleElem = mFormat.
writeXml( doc, context );
1110 textStyleElem.setAttribute( QStringLiteral(
"fieldName" ),
fieldName );
1111 textStyleElem.setAttribute( QStringLiteral(
"isExpression" ),
isExpression );
1112 QDomElement replacementElem = doc.createElement( QStringLiteral(
"substitutions" ) );
1114 textStyleElem.appendChild( replacementElem );
1115 textStyleElem.setAttribute( QStringLiteral(
"useSubstitutions" ),
useSubstitutions );
1118 QDomElement textFormatElem = doc.createElement( QStringLiteral(
"text-format" ) );
1119 textFormatElem.setAttribute( QStringLiteral(
"wrapChar" ),
wrapChar );
1120 textFormatElem.setAttribute( QStringLiteral(
"autoWrapLength" ),
autoWrapLength );
1122 textFormatElem.setAttribute( QStringLiteral(
"multilineAlign" ), static_cast< unsigned int >(
multilineAlign ) );
1123 textFormatElem.setAttribute( QStringLiteral(
"addDirectionSymbol" ),
addDirectionSymbol );
1124 textFormatElem.setAttribute( QStringLiteral(
"leftDirectionSymbol" ),
leftDirectionSymbol );
1127 textFormatElem.setAttribute( QStringLiteral(
"placeDirectionSymbol" ), static_cast< unsigned int >(
placeDirectionSymbol ) );
1128 textFormatElem.setAttribute( QStringLiteral(
"formatNumbers" ),
formatNumbers );
1129 textFormatElem.setAttribute( QStringLiteral(
"decimals" ),
decimals );
1130 textFormatElem.setAttribute( QStringLiteral(
"plussign" ),
plusSign );
1133 QDomElement placementElem = doc.createElement( QStringLiteral(
"placement" ) );
1134 placementElem.setAttribute( QStringLiteral(
"placement" ),
placement );
1135 placementElem.setAttribute( QStringLiteral(
"placementFlags" ), static_cast< unsigned int >(
placementFlags ) );
1136 placementElem.setAttribute( QStringLiteral(
"centroidWhole" ),
centroidWhole );
1137 placementElem.setAttribute( QStringLiteral(
"centroidInside" ),
centroidInside );
1139 placementElem.setAttribute( QStringLiteral(
"fitInPolygonOnly" ),
fitInPolygonOnly );
1140 placementElem.setAttribute( QStringLiteral(
"dist" ),
dist );
1143 placementElem.setAttribute( QStringLiteral(
"offsetType" ), static_cast< unsigned int >(
offsetType ) );
1144 placementElem.setAttribute( QStringLiteral(
"quadOffset" ), static_cast< unsigned int >(
quadOffset ) );
1145 placementElem.setAttribute( QStringLiteral(
"xOffset" ),
xOffset );
1146 placementElem.setAttribute( QStringLiteral(
"yOffset" ),
yOffset );
1149 placementElem.setAttribute( QStringLiteral(
"rotationAngle" ),
angleOffset );
1150 placementElem.setAttribute( QStringLiteral(
"preserveRotation" ),
preserveRotation );
1153 placementElem.setAttribute( QStringLiteral(
"priority" ),
priority );
1154 placementElem.setAttribute( QStringLiteral(
"repeatDistance" ),
repeatDistance );
1157 placementElem.setAttribute( QStringLiteral(
"overrunDistance" ),
overrunDistance );
1161 placementElem.setAttribute( QStringLiteral(
"geometryGenerator" ),
geometryGenerator );
1163 const QMetaEnum metaEnum( QMetaEnum::fromType<QgsWkbTypes::GeometryType>() );
1164 placementElem.setAttribute( QStringLiteral(
"geometryGeneratorType" ), metaEnum.valueToKey(
geometryGeneratorType ) );
1166 placementElem.setAttribute( QStringLiteral(
"layerType" ), metaEnum.valueToKey(
layerType ) );
1169 QDomElement renderingElem = doc.createElement( QStringLiteral(
"rendering" ) );
1170 renderingElem.setAttribute( QStringLiteral(
"drawLabels" ),
drawLabels );
1171 renderingElem.setAttribute( QStringLiteral(
"scaleVisibility" ),
scaleVisibility );
1172 renderingElem.setAttribute( QStringLiteral(
"scaleMin" ),
maximumScale );
1173 renderingElem.setAttribute( QStringLiteral(
"scaleMax" ),
minimumScale );
1174 renderingElem.setAttribute( QStringLiteral(
"fontLimitPixelSize" ),
fontLimitPixelSize );
1175 renderingElem.setAttribute( QStringLiteral(
"fontMinPixelSize" ),
fontMinPixelSize );
1176 renderingElem.setAttribute( QStringLiteral(
"fontMaxPixelSize" ),
fontMaxPixelSize );
1177 renderingElem.setAttribute( QStringLiteral(
"displayAll" ),
displayAll );
1178 renderingElem.setAttribute( QStringLiteral(
"upsidedownLabels" ), static_cast< unsigned int >(
upsidedownLabels ) );
1180 renderingElem.setAttribute( QStringLiteral(
"labelPerPart" ),
labelPerPart );
1181 renderingElem.setAttribute( QStringLiteral(
"mergeLines" ),
mergeLines );
1182 renderingElem.setAttribute( QStringLiteral(
"minFeatureSize" ), mThinningSettings.
minimumFeatureSize() );
1184 renderingElem.setAttribute( QStringLiteral(
"maxNumLabels" ), mThinningSettings.
maximumNumberLabels() );
1185 renderingElem.setAttribute( QStringLiteral(
"obstacle" ), mObstacleSettings.
isObstacle() );
1186 renderingElem.setAttribute( QStringLiteral(
"obstacleFactor" ), mObstacleSettings.
factor() );
1187 renderingElem.setAttribute( QStringLiteral(
"obstacleType" ), static_cast< unsigned int >( mObstacleSettings.
type() ) );
1188 renderingElem.setAttribute( QStringLiteral(
"zIndex" ),
zIndex );
1190 QDomElement ddElem = doc.createElement( QStringLiteral(
"dd_properties" ) );
1191 mDataDefinedProperties.
writeXml( ddElem, *sPropertyDefinitions() );
1193 QDomElement elem = doc.createElement( QStringLiteral(
"settings" ) );
1194 elem.appendChild( textStyleElem );
1195 elem.appendChild( textFormatElem );
1196 elem.appendChild( placementElem );
1197 elem.appendChild( renderingElem );
1198 elem.appendChild( ddElem );
1202 elem.setAttribute( QStringLiteral(
"calloutType" ), mCallout->type() );
1203 mCallout->saveProperties( doc, elem, context );
1211 mCallout.reset( callout );
1218 QPixmap pixmap( size );
1219 pixmap.fill( Qt::transparent );
1221 painter.begin( &pixmap );
1223 painter.setRenderHint( QPainter::Antialiasing );
1225 QRect rect( 0, 0, size.width(), size.height() );
1228 painter.setPen( Qt::NoPen );
1230 if ( ( background1.lightnessF() < 0.7 ) )
1232 background1 = background1.darker( 125 );
1236 background1 = background1.lighter( 125 );
1239 QLinearGradient linearGrad( QPointF( 0, 0 ), QPointF( 0, rect.height() ) );
1240 linearGrad.setColorAt( 0, background1 );
1241 linearGrad.setColorAt( 1, background2 );
1242 painter.setBrush( QBrush( linearGrad ) );
1243 if ( size.width() > 30 )
1245 painter.drawRoundedRect( rect, 6, 6 );
1250 painter.drawRect( rect );
1252 painter.setBrush( Qt::NoBrush );
1253 painter.setPen( Qt::NoPen );
1261 context.
setScaleFactor( QgsApplication::desktop()->logicalDpiX() / 25.4 );
1272 double ytrans = 0.0;
1278 const QStringList text = QStringList() << ( previewText.isEmpty() ? QObject::tr(
"Aa" ) : previewText );
1280 QRectF textRect = rect;
1281 textRect.setLeft( xtrans + padding );
1282 textRect.setWidth( rect.width() - xtrans - 2 * padding );
1284 if ( textRect.width() > 2000 )
1285 textRect.setWidth( 2000 - 2 * padding );
1287 const double bottom = textRect.height() / 2 + textHeight / 2;
1288 textRect.setTop( bottom - textHeight );
1289 textRect.setBottom( bottom );
1300 QRectF labelRect( textRect.left() + ( textRect.width() - textWidth ) / 2.0, textRect.top(), textWidth, textRect.height() );
1307 if ( size.width() > 30 )
1312 rect.width() - iconWidth * 3, rect.height() - iconWidth * 3,
1313 iconWidth * 2, iconWidth * 2 ), Qt::AlignRight | Qt::AlignBottom );
1317 painter.setBrush( Qt::NoBrush );
1319 if ( size.width() > 30 )
1321 painter.drawRoundedRect( rect, 6, 6 );
1326 painter.drawRect( rect );
1335 return QgsPalLabeling::checkMinimumSizeMM( ct, geom, minSize );
1345 QString textCopy( text );
1348 std::unique_ptr< QgsRenderContext > scopedRc;
1353 scopedRc->expressionContext().setFeature( *f );
1469 if ( wrapchr.isEmpty() )
1471 wrapchr = QStringLiteral(
"\n" );
1476 && ( !leftDirSymb.isEmpty() || !rightDirSymb.isEmpty() ) )
1478 QString dirSym = leftDirSymb;
1480 if ( fm->width( rightDirSymb ) > fm->width( dirSym ) )
1481 dirSym = rightDirSymb;
1485 textCopy.append( dirSym );
1489 textCopy.prepend( dirSym + QStringLiteral(
"\n" ) );
1493 double w = 0.0, h = 0.0, rw = 0.0, rh = 0.0;
1494 double labelHeight = fm->ascent() + fm->descent();
1496 int lines = multiLineSplit.size();
1498 switch ( orientation )
1502 h += fm->height() +
static_cast< double >( ( lines - 1 ) * labelHeight * multilineH );
1504 for (
const auto &line : multiLineSplit )
1506 w = std::max( w, fm->width( line ) );
1513 double letterSpacing = mFormat.
scaledFont( *context ).letterSpacing();
1514 double labelWidth = fm->maxWidth();
1515 w = labelWidth + ( lines - 1 ) * labelWidth * multilineH;
1517 int maxLineLength = 0;
1518 for (
const auto &line : multiLineSplit )
1520 maxLineLength = std::max( maxLineLength, line.length() );
1522 h = fm->ascent() * maxLineLength + ( maxLineLength - 1 ) * letterSpacing;
1528 double widthHorizontal = 0.0;
1529 for (
const auto &line : multiLineSplit )
1531 widthHorizontal = std::max( w, fm->width( line ) );
1534 double widthVertical = 0.0;
1535 double letterSpacing = mFormat.
scaledFont( *context ).letterSpacing();
1536 double labelWidth = fm->maxWidth();
1537 widthVertical = labelWidth + ( lines - 1 ) * labelWidth * multilineH;
1539 double heightHorizontal = 0.0;
1540 heightHorizontal += fm->height() +
static_cast< double >( ( lines - 1 ) * labelHeight * multilineH );
1542 double heightVertical = 0.0;
1543 int maxLineLength = 0;
1544 for (
const auto &line : multiLineSplit )
1546 maxLineLength = std::max( maxLineLength, line.length() );
1548 heightVertical = fm->ascent() * maxLineLength + ( maxLineLength - 1 ) * letterSpacing;
1550 w = widthHorizontal;
1551 rw = heightVertical;
1552 h = heightHorizontal;
1560 labelX = std::fabs( ptSize.
x() -
ptZero.
x() );
1561 labelY = std::fabs( ptSize.
y() -
ptZero.
y() );
1566 if ( rotatedLabelX && rotatedLabelY )
1568 *rotatedLabelX = rw * uPP;
1569 *rotatedLabelY = rh * uPP;
1577 Q_ASSERT( labelFeature );
1583 bool isObstacle = mObstacleSettings.
isObstacle();
1591 registerObstacleFeature( f, context, labelFeature, obstacleGeometry );
1603 if ( obstacleGeometry.
isNull() )
1616 dataDefinedValues.clear();
1633 if ( useScaleVisibility )
1646 maxScale = 1 / std::fabs( maxScale );
1665 minScale = 1 / std::fabs( minScale );
1674 QFont labelFont = mFormat.
font();
1680 if ( exprVal.isValid() )
1682 QString units = exprVal.toString();
1683 if ( !units.isEmpty() )
1693 double fontSize = mFormat.
size();
1699 if ( fontSize <= 0.0 )
1706 if ( fontPixelSize < 1 )
1710 labelFont.setPixelSize( fontPixelSize );
1722 if ( fontMinPixel > labelFont.pixelSize() || labelFont.pixelSize() > fontMaxPixel )
1734 labelFont.setCapitalization( QFont::MixedCase );
1736 parseTextStyle( labelFont, fontunits, context );
1739 parseTextFormatting( context );
1740 parseTextBuffer( context );
1741 parseTextMask( context );
1742 parseShapeBackground( context );
1743 parseDropShadow( context );
1764 labelText = result.isNull() ? QString() : result.toString();
1769 labelText = v.isNull() ? QString() : v.toString();
1781 if ( mFormat.
font().capitalization() != QFont::MixedCase )
1789 if ( exprVal.isValid() )
1791 QString fcase = exprVal.toString().trimmed();
1792 QgsDebugMsgLevel( QStringLiteral(
"exprVal FontCase:%1" ).arg( fcase ), 4 );
1794 if ( !fcase.isEmpty() )
1796 if ( fcase.compare( QLatin1String(
"NoChange" ), Qt::CaseInsensitive ) == 0 )
1800 else if ( fcase.compare( QLatin1String(
"Upper" ), Qt::CaseInsensitive ) == 0 )
1804 else if ( fcase.compare( QLatin1String(
"Lower" ), Qt::CaseInsensitive ) == 0 )
1808 else if ( fcase.compare( QLatin1String(
"Capitalize" ), Qt::CaseInsensitive ) == 0 )
1823 if ( evalFormatNumbers )
1827 if ( decimalPlaces <= 0 )
1833 QVariant textV( labelText );
1835 double d = textV.toDouble( &ok );
1838 QString numberFormat;
1839 if ( d > 0 && signPlus )
1841 numberFormat.append(
'+' );
1843 numberFormat.append(
"%1" );
1844 labelText = numberFormat.arg( d, 0,
'f', decimalPlaces );
1849 std::unique_ptr<QFontMetricsF> labelFontMetrics(
new QFontMetricsF( labelFont ) );
1850 double labelX, labelY, rotatedLabelX, rotatedLabelY;
1856 double maxcharanglein = 20.0;
1857 double maxcharangleout = -20.0;
1872 maxcharanglein = qBound( 20.0, static_cast< double >( maxcharanglePt.x() ), 60.0 );
1873 maxcharangleout = qBound( 20.0, static_cast< double >( maxcharanglePt.y() ), 95.0 );
1877 maxcharangleout = -( std::fabs( maxcharangleout ) );
1885 if ( exprVal.isValid() )
1887 QString str = exprVal.toString().trimmed();
1888 QgsDebugMsgLevel( QStringLiteral(
"exprVal CentroidWhole:%1" ).arg( str ), 4 );
1890 if ( !str.isEmpty() )
1892 if ( str.compare( QLatin1String(
"Visible" ), Qt::CaseInsensitive ) == 0 )
1894 wholeCentroid =
false;
1896 else if ( str.compare( QLatin1String(
"Whole" ), Qt::CaseInsensitive ) == 0 )
1898 wholeCentroid =
true;
1912 std::unique_ptr<QgsGeometry> scopedClonedGeom;
1919 geom = simplifier.
simplify( geom );
1929 bool doClip =
false;
1930 if ( !centroidPoly || !wholeCentroid )
1940 permissibleZone = geom;
1979 if ( !geos_geom_clone )
2008 bool dataDefinedPosition =
false;
2009 bool layerDefinedRotation =
false;
2010 bool dataDefinedRotation =
false;
2011 double xPos = 0.0, yPos = 0.0,
angle = 0.0;
2012 bool ddXPos =
false, ddYPos =
false;
2013 double quadOffsetX = 0.0, quadOffsetY = 0.0;
2014 double offsetX = 0.0, offsetY = 0.0;
2026 bool ddFixedQuad =
false;
2030 context.expressionContext().setOriginalValueVariable( static_cast< int >( quadOff ) );
2032 if ( exprVal.isValid() )
2035 int quadInt = exprVal.toInt( &ok );
2036 if ( ok && 0 <= quadInt && quadInt <= 8 )
2104 if ( exprVal.isValid() )
2106 QString units = exprVal.toString().trimmed();
2107 if ( !units.isEmpty() )
2113 offUnit = decodedUnits;
2129 layerDefinedRotation =
true;
2137 context.expressionContext().setOriginalValueVariable(
angleOffset );
2139 if ( exprVal.isValid() )
2142 double rotD = exprVal.toDouble( &ok );
2145 dataDefinedRotation =
true;
2149 angle = ( 360 - rotD ) * M_PI / 180.0;
2157 if ( exprVal.isValid() )
2159 if ( !exprVal.isNull() )
2160 xPos = exprVal.toDouble( &ddXPos );
2165 if ( exprVal.isValid() )
2168 if ( !exprVal.isNull() )
2169 yPos = exprVal.toDouble( &ddYPos );
2171 if ( ddXPos && ddYPos )
2173 dataDefinedPosition =
true;
2175 if ( layerDefinedRotation && !dataDefinedRotation )
2184 if ( exprVal.isValid() )
2186 QString haliString = exprVal.toString();
2187 if ( haliString.compare( QLatin1String(
"Center" ), Qt::CaseInsensitive ) == 0 )
2189 xdiff -= labelX / 2.0;
2191 else if ( haliString.compare( QLatin1String(
"Right" ), Qt::CaseInsensitive ) == 0 )
2202 if ( exprVal.isValid() )
2204 QString valiString = exprVal.toString();
2205 if ( valiString.compare( QLatin1String(
"Bottom" ), Qt::CaseInsensitive ) != 0 )
2207 if ( valiString.compare( QLatin1String(
"Top" ), Qt::CaseInsensitive ) == 0 )
2213 double descentRatio = labelFontMetrics->descent() / labelFontMetrics->height();
2214 if ( valiString.compare( QLatin1String(
"Base" ), Qt::CaseInsensitive ) == 0 )
2216 ydiff -= labelY * descentRatio;
2220 double capHeightRatio = ( labelFontMetrics->boundingRect(
'H' ).height() + 1 + labelFontMetrics->descent() ) / labelFontMetrics->height();
2221 ydiff -= labelY * capHeightRatio;
2222 if ( valiString.compare( QLatin1String(
"Half" ), Qt::CaseInsensitive ) == 0 )
2224 ydiff += labelY * ( capHeightRatio - descentRatio ) / 2.0;
2232 if ( dataDefinedRotation )
2235 double xd = xdiff * std::cos(
angle ) - ydiff * std::sin(
angle );
2236 double yd = xdiff * std::sin(
angle ) + ydiff * std::cos(
angle );
2271 bool alwaysShow =
false;
2282 context.expressionContext().setOriginalValueVariable( repeatDist );
2291 if ( exprVal.isValid() )
2293 QString units = exprVal.toString().trimmed();
2294 if ( !units.isEmpty() )
2300 repeatUnits = decodedUnits;
2318 context.expressionContext().setOriginalValueVariable( overrunDistanceEval );
2332 if ( !dataDefinedPosition )
2336 context.expressionContext().setOriginalValueVariable(
labelPerPart );
2352 ( *labelFeature )->setFixedPosition(
QgsPointXY( xPos, yPos ) );
2354 ( *labelFeature )->setHasFixedAngle( dataDefinedRotation || ( !dataDefinedPosition && !
qgsDoubleNear(
angle, 0.0 ) ) );
2355 ( *labelFeature )->setFixedAngle(
angle );
2356 ( *labelFeature )->setQuadOffset( QPointF( quadOffsetX, quadOffsetY ) );
2357 ( *labelFeature )->setPositionOffset(
QgsPointXY( offsetX, offsetY ) );
2358 ( *labelFeature )->setOffsetType( offsetType );
2359 ( *labelFeature )->setAlwaysShow( alwaysShow );
2360 ( *labelFeature )->setRepeatDistance( repeatDist );
2361 ( *labelFeature )->setLabelText( labelText );
2362 ( *labelFeature )->setPermissibleZone( permissibleZone );
2363 ( *labelFeature )->setOverrunDistance( overrunDistanceEval );
2364 ( *labelFeature )->setOverrunSmoothDistance( overrunSmoothDist );
2365 ( *labelFeature )->setLabelAllParts( labelAll );
2369 ( *labelFeature )->setSymbolSize( QSizeF( obstacleGeometry.
boundingBox().
width(),
2375 double topMargin = std::max( 0.25 * labelFontMetrics->ascent(), 0.0 );
2376 double bottomMargin = 1.0 + labelFontMetrics->descent();
2377 QgsMargins vm( 0.0, topMargin, 0.0, bottomMargin );
2379 ( *labelFeature )->setVisualMargin( vm );
2382 QgsDebugMsgLevel( QStringLiteral(
"PAL font stored definedFont: %1, Style: %2" ).arg( labelFont.toString(), labelFont.styleName() ), 4 );
2388 labelFontMetrics.get(),
xform, maxcharanglein, maxcharangleout );
2394 double distance =
dist;
2397 context.expressionContext().setOriginalValueVariable( distance );
2406 if ( exprVal.isValid() )
2408 QString units = exprVal.toString().trimmed();
2409 QgsDebugMsgLevel( QStringLiteral(
"exprVal DistanceUnits:%1" ).arg( units ), 4 );
2410 if ( !units.isEmpty() )
2416 distUnit = decodedUnits;
2421 distance = context.convertToPainterUnits( distance, distUnit,
distMapUnitScale );
2427 distance = ( distance < 0 ? -1 : 1 ) * std::max( std::fabs( distance ), 1.0 );
2433 ( *labelFeature )->setDistLabel( d );
2438 ( *labelFeature )->setHasFixedQuadrant(
true );
2441 QgsLabeling::LinePlacementFlags featureArrangementFlags =
static_cast< QgsLabeling::LinePlacementFlags
>(
placementFlags );
2446 if ( !dataDefinedLineArrangement.isEmpty() )
2451 ( *labelFeature )->setArrangementFlags( featureArrangementFlags );
2457 context.expressionContext().setOriginalValueVariable( z );
2460 ( *labelFeature )->setZIndex( z );
2465 context.expressionContext().setOriginalValueVariable(
priority );
2467 if ( exprVal.isValid() )
2470 double priorityD = exprVal.toDouble( &ok );
2473 priorityD = qBound( 0.0, priorityD, 10.0 );
2474 priorityD = 1 - priorityD / 10.0;
2475 ( *labelFeature )->setPriority( priorityD );
2487 if ( positionOrder.isEmpty() )
2488 positionOrder = *DEFAULT_PLACEMENT_ORDER();
2494 if ( !dataDefinedOrder.isEmpty() )
2499 ( *labelFeature )->setPredefinedPositionOrder( positionOrder );
2510 if ( !obstacleGeometry.
isNull() )
2512 geom = obstacleGeometry;
2526 std::unique_ptr<QgsGeometry> scopedClonedGeom;
2532 geom = simplifier.
simplify( geom );
2536 std::unique_ptr<QgsGeometry> scopedPreparedGeom;
2544 if ( !geos_geom_clone )
2548 *obstacleFeature =
new QgsLabelFeature( f.
id(), std::move( geos_geom_clone ), QSizeF( 0, 0 ) );
2554 ( *obstacleFeature )->setObstacleSettings( os );
2559 bool QgsPalLayerSettings::dataDefinedValEval( DataDefinedValueType valType,
2563 if ( !mDataDefinedProperties.
isActive( p ) )
2567 exprVal = mDataDefinedProperties.
value( p, context );
2568 if ( exprVal.isValid() )
2574 bool bol = exprVal.toBool();
2575 dataDefinedValues.insert( p, QVariant( bol ) );
2581 int size = exprVal.toInt( &ok );
2585 dataDefinedValues.insert( p, QVariant( size ) );
2593 int size = exprVal.toInt( &ok );
2595 if ( ok && size > 0 )
2597 dataDefinedValues.insert( p, QVariant( size ) );
2605 double size = exprVal.toDouble( &ok );
2609 dataDefinedValues.insert( p, QVariant( size ) );
2617 double size = exprVal.toDouble( &ok );
2619 if ( ok && size > 0.0 )
2621 dataDefinedValues.insert( p, QVariant( size ) );
2629 double rot = exprVal.toDouble( &ok );
2632 if ( rot < -180.0 && rot >= -360 )
2636 if ( rot > 180.0 && rot <= 360 )
2640 if ( rot >= -180 && rot <= 180 )
2642 dataDefinedValues.insert( p, QVariant( rot ) );
2651 int size = exprVal.toInt( &ok );
2652 if ( ok && size >= 0 && size <= 100 )
2654 dataDefinedValues.insert( p, QVariant( size ) );
2661 QString str = exprVal.toString();
2663 dataDefinedValues.insert( p, QVariant( str ) );
2668 QString unitstr = exprVal.toString().trimmed();
2670 if ( !unitstr.isEmpty() )
2679 QString colorstr = exprVal.toString().trimmed();
2682 if ( color.isValid() )
2684 dataDefinedValues.insert( p, QVariant( color ) );
2691 QString joinstr = exprVal.toString().trimmed();
2693 if ( !joinstr.isEmpty() )
2702 QString blendstr = exprVal.toString().trimmed();
2704 if ( !blendstr.isEmpty() )
2717 dataDefinedValues.insert( p, res );
2728 dataDefinedValues.insert( p, res );
2738 void QgsPalLayerSettings::parseTextStyle( QFont &labelFont,
2751 QString ddFontFamily;
2756 if ( exprVal.isValid() )
2758 QString family = exprVal.toString().trimmed();
2759 QgsDebugMsgLevel( QStringLiteral(
"exprVal Font family:%1" ).arg( family ), 4 );
2761 if ( labelFont.family() != family )
2767 ddFontFamily = family;
2774 QString ddFontStyle;
2778 if ( exprVal.isValid() )
2780 QString fontstyle = exprVal.toString().trimmed();
2781 QgsDebugMsgLevel( QStringLiteral(
"exprVal Font style:%1" ).arg( fontstyle ), 4 );
2782 ddFontStyle = fontstyle;
2787 bool ddBold =
false;
2795 bool ddItalic =
false;
2805 QFont appFont = QApplication::font();
2806 bool newFontBuilt =
false;
2807 if ( ddBold || ddItalic )
2810 newFont = QFont( !ddFontFamily.isEmpty() ? ddFontFamily : labelFont.family() );
2811 newFontBuilt =
true;
2812 newFont.setBold( ddBold );
2813 newFont.setItalic( ddItalic );
2815 else if ( !ddFontStyle.isEmpty()
2816 && ddFontStyle.compare( QLatin1String(
"Ignore" ), Qt::CaseInsensitive ) != 0 )
2818 if ( !ddFontFamily.isEmpty() )
2821 QFont styledfont = mFontDB.font( ddFontFamily, ddFontStyle, appFont.pointSize() );
2822 if ( appFont != styledfont )
2824 newFont = styledfont;
2825 newFontBuilt =
true;
2832 else if ( !ddFontFamily.isEmpty() )
2834 if ( ddFontStyle.compare( QLatin1String(
"Ignore" ), Qt::CaseInsensitive ) != 0 )
2837 QFont styledfont = mFontDB.font( ddFontFamily, mFormat.
namedStyle(), appFont.pointSize() );
2838 if ( appFont != styledfont )
2840 newFont = styledfont;
2841 newFontBuilt =
true;
2846 newFont = QFont( ddFontFamily );
2847 newFontBuilt =
true;
2855 newFont.setPixelSize( labelFont.pixelSize() );
2856 newFont.setUnderline( labelFont.underline() );
2857 newFont.setStrikeOut( labelFont.strikeOut() );
2858 newFont.setWordSpacing( labelFont.wordSpacing() );
2859 newFont.setLetterSpacing( QFont::AbsoluteSpacing, labelFont.letterSpacing() );
2861 labelFont = newFont;
2865 double wordspace = labelFont.wordSpacing();
2874 double letterspace = labelFont.letterSpacing();
2887 labelFont.setStrikeOut( strikeout );
2895 labelFont.setUnderline( underline );
2921 drawBuffer = exprVal.toBool();
2935 double bufrSize = buffer.
size();
2938 bufrSize = exprVal.toDouble();
2942 double bufferOpacity = buffer.
opacity() * 100;
2945 bufferOpacity = exprVal.toDouble();
2948 drawBuffer = ( drawBuffer && bufrSize > 0.0 && bufferOpacity > 0 );
2978 bool maskEnabled = mask.
enabled();
2981 maskEnabled = exprVal.toBool();
2990 double bufrSize = mask.
size();
2993 bufrSize = exprVal.toDouble();
2997 double opacity = mask.
opacity() * 100;
3000 opacity = exprVal.toDouble();
3003 maskEnabled = ( maskEnabled && bufrSize > 0.0 && opacity > 0 );
3028 wrapchr = exprVal.toString();
3034 evalAutoWrapLength = exprVal.toInt();
3045 if ( exprVal.isValid() )
3047 QString str = exprVal.toString().trimmed();
3048 QgsDebugMsgLevel( QStringLiteral(
"exprVal MultiLineAlignment:%1" ).arg( str ), 4 );
3050 if ( !str.isEmpty() )
3055 if ( str.compare( QLatin1String(
"Center" ), Qt::CaseInsensitive ) == 0 )
3059 else if ( str.compare( QLatin1String(
"Right" ), Qt::CaseInsensitive ) == 0 )
3063 else if ( str.compare( QLatin1String(
"Follow" ), Qt::CaseInsensitive ) == 0 )
3078 if ( exprVal.isValid() )
3080 QString str = exprVal.toString().trimmed();
3081 if ( !str.isEmpty() )
3090 drawDirSymb = exprVal.toBool();
3103 if ( exprVal.isValid() )
3105 QString str = exprVal.toString().trimmed();
3106 QgsDebugMsgLevel( QStringLiteral(
"exprVal DirSymbPlacement:%1" ).arg( str ), 4 );
3108 if ( !str.isEmpty() )
3113 if ( str.compare( QLatin1String(
"Above" ), Qt::CaseInsensitive ) == 0 )
3117 else if ( str.compare( QLatin1String(
"Below" ), Qt::CaseInsensitive ) == 0 )
3132 void QgsPalLayerSettings::parseShapeBackground(
QgsRenderContext &context )
3139 bool drawShape = background.
enabled();
3142 drawShape = exprVal.toBool();
3151 double shapeOpacity = background.
opacity() * 100;
3154 shapeOpacity = 100.0 * exprVal.toDouble();
3157 drawShape = ( drawShape && shapeOpacity > 0 );
3171 if ( exprVal.isValid() )
3173 QString skind = exprVal.toString().trimmed();
3174 QgsDebugMsgLevel( QStringLiteral(
"exprVal ShapeKind:%1" ).arg( skind ), 4 );
3176 if ( !skind.isEmpty() )
3185 QString svgPath = background.
svgFile();
3190 if ( exprVal.isValid() )
3192 QString svgfile = exprVal.toString().trimmed();
3193 QgsDebugMsgLevel( QStringLiteral(
"exprVal ShapeSVGFile:%1" ).arg( svgfile ), 4 );
3206 if ( exprVal.isValid() )
3208 QString stype = exprVal.toString().trimmed();
3209 QgsDebugMsgLevel( QStringLiteral(
"exprVal ShapeSizeType:%1" ).arg( stype ), 4 );
3211 if ( !stype.isEmpty() )
3220 double ddShpSizeX = background.
size().width();
3223 ddShpSizeX = exprVal.toDouble();
3227 double ddShpSizeY = background.
size().height();
3230 ddShpSizeY = exprVal.toDouble();
3236 && ( svgPath.isEmpty()
3237 || ( !svgPath.isEmpty()
3239 && ddShpSizeX == 0.0 ) ) )
3247 && ddShpSizeX == 0.0 ) ) )
3254 && ( ddShpSizeX == 0.0 || ddShpSizeY == 0.0 ) )
3277 if ( exprVal.isValid() )
3279 QString rotstr = exprVal.toString().trimmed();
3280 QgsDebugMsgLevel( QStringLiteral(
"exprVal ShapeRotationType:%1" ).arg( rotstr ), 4 );
3282 if ( !rotstr.isEmpty() )
3333 bool drawShadow = shadow.
enabled();
3336 drawShadow = exprVal.toBool();
3345 double shadowOpacity = shadow.
opacity() * 100;
3348 shadowOpacity = exprVal.toDouble();
3355 shadowOffDist = exprVal.toDouble();
3362 shadowRad = exprVal.toDouble();
3365 drawShadow = ( drawShadow && shadowOpacity > 0 && !( shadowOffDist == 0.0 && shadowRad == 0.0 ) );
3380 if ( exprVal.isValid() )
3382 QString str = exprVal.toString().trimmed();
3383 QgsDebugMsgLevel( QStringLiteral(
"exprVal ShadowUnder:%1" ).arg( str ), 4 );
3385 if ( !str.isEmpty() )
3458 QStringList multiLineSplit;
3459 if ( !wrapCharacter.isEmpty() && wrapCharacter != QLatin1String(
"\n" ) )
3462 const QStringList lines = text.split( wrapCharacter );
3463 for (
const QString &line : lines )
3465 multiLineSplit.append( line.split(
'\n' ) );
3470 multiLineSplit = text.split(
'\n' );
3474 if ( autoWrapLength != 0 )
3476 QStringList autoWrappedLines;
3477 autoWrappedLines.reserve( multiLineSplit.count() );
3478 for (
const QString &line : qgis::as_const( multiLineSplit ) )
3480 autoWrappedLines.append(
QgsStringUtils::wordWrap( line, autoWrapLength, useMaxLineLengthWhenAutoWrapping ).split(
'\n' ) );
3482 multiLineSplit = autoWrappedLines;
3484 return multiLineSplit;
3489 QStringList graphemes;
3490 QTextBoundaryFinder boundaryFinder( QTextBoundaryFinder::Grapheme, text );
3491 int currentBoundary = -1;
3492 int previousBoundary = 0;
3493 while ( ( currentBoundary = boundaryFinder.toNextBoundary() ) > 0 )
3495 graphemes << text.mid( previousBoundary, currentBoundary - previousBoundary );
3496 previousBoundary = currentBoundary;
3526 QgsDebugMsgLevel( QStringLiteral(
"Ignoring feature due to transformation exception" ), 4 );
3532 return std::isfinite( point.
x() ) && std::isfinite( point.
y() );
3535 cp->removeInvalidRings();
3545 QgsDebugMsg( QStringLiteral(
"Error rotating geometry" ).arg( geom.
asWkt() ) );
3559 QVector< QgsGeometry> parts;
3560 parts.reserve( qgsgeometry_cast< const QgsGeometryCollection * >( geom.
constGet() )->numGeometries() );
3564 if ( !partGeom.isGeosValid() )
3566 partGeom = partGeom.
buffer( 0, 0 );
3568 parts.append( partGeom );
3575 if ( bufferGeom.
isNull() )
3577 QgsDebugMsg( QStringLiteral(
"Could not repair geometry: %1" ).arg( bufferGeom.
lastError() ) );
3584 if ( !clipGeometry.
isNull() &&
3620 double length = geom.
length();
3621 if ( length >= 0.0 )
3623 return ( length >= ( minSize * mapUnitsPerMM ) );
3628 double area = geom.
area();
3631 return ( std::sqrt( area ) >= ( minSize * mapUnitsPerMM ) );
3639 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
3642 bool changed =
false;
3648 format.
setColor( ddColor.value<QColor>() );
3673 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
3735 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
3738 bool changed =
false;
3786 buffer.
setColor( ddColor.value<QColor>() );
3813 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
3815 if ( ddValues.isEmpty() )
3819 bool changed =
false;
3879 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
3882 bool changed =
false;
3922 QSizeF size = background.
size();
3929 QSizeF size = background.
size();
4030 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues )
4033 bool changed =
false;
4092 shadow.
setColor( ddColor.value<QColor>() );
4130 #if 0 // TODO: generalize some of this 4133 double cx = lp->
getX() + w / 2.0;
4134 double cy = lp->
getY() + h / 2.0;
4137 double sw = w * scale;
4138 double sh = h * scale;
4139 QRectF rect( -sw / 2, -sh / 2, sw, sh );
4145 if ( lp->
getFeaturePart()->getLayer()->getArrangement() != P_POINT &&
4146 lp->
getFeaturePart()->getLayer()->getArrangement() != P_POINT_OVER &&
4149 painter->rotate( rotation );
4152 painter->translate( rect.bottomLeft() );
4153 painter->rotate( -lp->
getAlpha() * 180 / M_PI );
4154 painter->translate( -rect.bottomLeft() );
4157 QRectF rect( 0, 0, outPt2.
x() - outPt.
x(), outPt2.
y() - outPt.
y() );
4158 painter->translate( QPointF( outPt.
x(), outPt.
y() ) );
4159 painter->rotate( -lp->
getAlpha() * 180 / M_PI );
4164 painter->setPen( QColor( 255, 0, 0, 64 ) );
4168 painter->setPen( QColor( 0, 0, 0, 64 ) );
4170 painter->drawRect( rect );
4174 rect.moveTo( outPt.
x(), outPt.
y() );
4180 drawLabelCandidateRect( lp->
nextPart(), painter,
xform, candidates );
4192 QList<QgsLabelPosition> positions;
4194 QList<QgsLabelPosition *> positionPointers;
4195 if ( mLabelSearchTree )
4197 mLabelSearchTree->label( p, positionPointers );
4198 QList<QgsLabelPosition *>::const_iterator pointerIt = positionPointers.constBegin();
4199 for ( ; pointerIt != positionPointers.constEnd(); ++pointerIt )
4210 QList<QgsLabelPosition> positions;
4212 QList<QgsLabelPosition *> positionPointers;
4213 if ( mLabelSearchTree )
4215 mLabelSearchTree->labelsInRect( r, positionPointers );
4216 QList<QgsLabelPosition *>::const_iterator pointerIt = positionPointers.constBegin();
4217 for ( ; pointerIt != positionPointers.constEnd(); ++pointerIt )
4228 mLabelSearchTree->setMapSettings( settings );
void setProperty(int key, const QgsProperty &property)
Adds a property to the collection and takes ownership of it.
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
Label on bottom right of point.
void setSymbol(const QgsSymbol *symbol)
Sets the feature symbol associated with this label.
Render units (eg mm/pixels/map units)
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
TextOrientation
Text orientation.
Class for parsing and evaluation of expressions (formerly called "search strings").
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
static const QgsPropertiesDefinition & propertyDefinitions()
Returns the labeling property definitions.
LabelPosition * nextPart() const
Returns the next part of this label position (i.e.
double xOffset
Horizontal offset of label.
The class is used as a container of context for various read/write operations on other objects...
QString geometryGenerator
The geometry generator expression. Null if disabled.
Shape transparency (deprecated)
QColor strokeColor() const
Returns the color used for outlining the background shape.
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.
void setObstacleGeometry(const QgsGeometry &obstacleGeom)
Sets the label's obstacle geometry, if different to the feature geometry.
bool contains(const QgsRectangle &rect) const
Returns true when rectangle contains other rectangle.
void setScale(int scale)
Sets the scaling used for the drop shadow (in percentage of original size).
void setIsObstacle(bool isObstacle)
Sets whether features are obstacles to labels of other layers.
void setLineHeight(double height)
Sets the line height for text.
void setRadiiUnit(QgsUnitTypes::RenderUnit units)
Sets the units used for the shape's radii.
A rectangle specified with double values.
void setStrokeWidth(double width)
Sets the width of the shape's stroke (stroke).
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
double rendererScale() const
Returns the renderer map scale.
Label on bottom-left of point.
RotationType
Methods for determining the rotation of the background shape.
const QgsPathResolver & pathResolver() const
Returns the path resolver for conversion between relative and absolute paths during rendering operati...
double maxCurvedCharAngleOut
Maximum angle between outside curved label characters (valid range -20.0 to -95.0) ...
Abstract base class for callout renderers.
double maximumScale
The maximum map scale (i.e.
QString leftDirectionSymbol
String to use for left direction arrows.
static QgsCalloutRegistry * calloutRegistry()
Returns the application's callout registry, used for managing callout types.
Horizontally or vertically oriented text based on rotation (only available for map labeling) ...
void setOpacity(double opacity)
Sets the text's opacity.
Extends QApplication to provide access to QGIS specific resources such as theme paths, database paths etc.
void setMask(const QgsTextMaskSettings &maskSettings)
Sets the text's masking settings.
Positive integer values (including 0)
void setOffsetUnit(QgsUnitTypes::RenderUnit units)
Sets the units used for the shadow's offset.
static QPointF toPoint(const QVariant &value, bool *ok=nullptr)
Converts a value to a point.
QgsUnitTypes::RenderUnit repeatDistanceUnit
Units for repeating labels for a single feature.
QSizeF radii() const
Returns the radii used for rounding the corners of shapes.
QSizeF size() const
Returns the size of the background shape.
double opacity() const
Returns the text's opacity.
const QgsVectorSimplifyMethod & vectorSimplifyMethod() const
Returns the simplification settings to use when rendering vector layers.
void setSizeUnit(QgsUnitTypes::RenderUnit unit)
Sets the units used for the shape's size.
QgsMapUnitScale overrunDistanceMapUnitScale
Map unit scale for label overrun distance.
void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Read settings from a DOM element.
void setOrientation(TextOrientation orientation)
Sets the orientation for the text.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
void registerFeature(const QgsFeature &f, QgsRenderContext &context, QgsLabelFeature **labelFeature=nullptr, QgsGeometry obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling.
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
QPointF offset() const
Returns the offset used for drawing the background shape.
QColor fillColor() const
Returns the color used for filing the background shape.
virtual void stopRender(QgsRenderContext &context)
Finalises the callout after a set of rendering operations on the specified render context...
Q_GLOBAL_STATIC_WITH_ARGS(PredefinedPointPositionVector, DEFAULT_PLACEMENT_ORDER,({ QgsPalLayerSettings::TopRight, QgsPalLayerSettings::TopLeft, QgsPalLayerSettings::BottomRight, QgsPalLayerSettings::BottomLeft, QgsPalLayerSettings::MiddleRight, QgsPalLayerSettings::MiddleLeft, QgsPalLayerSettings::TopSlightlyRight, QgsPalLayerSettings::BottomSlightlyRight })) void QgsPalLayerSettings
Abstract base class for all rendered symbols.
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
static QgsTextBackgroundSettings::RotationType decodeBackgroundRotationType(const QString &string)
Decodes a string representation of a background rotation type to a type.
double valueAsDouble(int key, const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a double...
void render(QgsRenderContext &context, QRectF rect, const double angle, const QgsGeometry &anchor, QgsCalloutContext &calloutContext)
Renders the callout onto the specified render context.
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
static const double UI_SCALE_FACTOR
UI scaling factor.
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...
static QString encodeSize(QSizeF size)
Encodes a QSizeF to a string.
QVector< QgsPalLayerSettings::PredefinedPointPosition > PredefinedPointPositionVector
double angleOffset
Label rotation, in degrees clockwise.
virtual bool readXml(const QDomElement &collectionElem, const QgsPropertiesDefinition &definitions)
Reads property collection state from an XML element.
bool formatNumbers
Set to true to format numeric label text as numbers (e.g.
Contains additional contextual information about the context in which a callout is being rendered...
A class to query the labeling structure at a given point (small wrapper around pal RTree class) ...
UpsideDownLabels upsidedownLabels
Controls whether upside down labels are displayed and how they are handled.
Label on top-left of point.
SimplifyAlgorithm simplifyAlgorithm() const
Gets the local simplification algorithm of the vector layer managed.
Contains settings related to how the label engine removes candidate label positions and reduces the n...
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...
ShadowPlacement
Placement positions for text shadow.
Place direction symbols on below label.
Arranges candidates over a point (or centroid of a polygon), or at a preset offset from the point...
QgsTextShadowSettings & shadow()
Returns a reference to the text drop shadow settings.
double blurRadius() const
Returns the blur radius for the shadow.
static void drawLabelCandidateRect(pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList< QgsLabelCandidate > *candidates=nullptr)
double getY(int i=0) const
Returns the down-left y coordinate.
Arranges candidates following the curvature of a line feature. Applies to line layers only...
double opacity() const
Returns the background shape's opacity.
void setStrokeColor(const QColor &color)
Sets the color used for outlining the background shape.
void setSize(double size)
Sets the size of the buffer.
A class to represent a 2D point.
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry...
double strokeWidth() const
Returns the width of the shape's stroke (stroke).
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
void setSizeUnit(QgsUnitTypes::RenderUnit unit)
Sets the units used for the buffer size.
OperationResult rotate(double rotation, const QgsPointXY ¢er)
Rotate this geometry around the Z axis.
double offsetDistance() const
Returns the distance for offsetting the position of the shadow from the text.
int decimals
Number of decimal places to show for numeric labels.
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
void setJoinStyle(Qt::PenJoinStyle style)
Sets the join style used for drawing the buffer.
double repeatDistance
Distance for repeating labels for a single feature.
QVariant evaluate()
Evaluate the feature and return the result.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
Candidates are placed in predefined positions around a point. Preference is given to positions with g...
#define Q_NOWARN_DEPRECATED_PUSH
QuadrantPosition quadOffset
Sets the quadrant in which to offset labels from feature.
QgsUnitTypes::RenderUnit offsetUnits
Units for offsets of label.
void setOffsetUnit(QgsUnitTypes::RenderUnit units)
Sets the units used for the shape's offset.
static QgsTextBackgroundSettings::SizeType decodeBackgroundSizeType(const QString &string)
Decodes a string representation of a background size type to a type.
static QgsProperty fromExpression(const QString &expression, bool isActive=true)
Returns a new ExpressionBasedProperty created from the specified expression.
Shadow transparency (deprecated)
QColor color() const
Returns the color that text will be rendered in.
double yOffset
Vertical offset of label.
Class that adds extra information to QgsLabelFeature for text labels.
double size() const
Returns the size of the buffer.
Curve polygon geometry type.
QString evalErrorString() const
Returns evaluation error.
void setBlurRadius(double blurRadius)
Sets the blur radius for the shadow.
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
static QgsLabeling::LinePlacementFlags decodeLinePlacementFlags(const QString &string)
Decodes a string to set of line placement flags.
void setDefinedFont(const QFont &f)
Sets font to be used for rendering.
void setOpacity(double opacity)
Sets the shadow's opacity.
X-coordinate data defined label position.
Min scale (deprecated, for old project compatibility only)
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
Container of fields for a vector layer.
Label on top-right of point.
bool addDirectionSymbol
If true, '<' or '>' (or custom strings set via leftDirectionSymbol and rightDirectionSymbol) will be ...
void setFactor(double factor)
Sets the obstacle factor, where 1.0 = default, < 1.0 more likely to be covered by labels...
bool geometryGeneratorEnabled
Defines if the geometry generator is enabled or not. If disabled, the standard geometry will be taken...
A geometry is the spatial representation of a feature.
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
bool drawLabels
Whether to draw labels for this layer.
QgsGeometry buffer(double distance, int segments) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
void setBackground(const QgsTextBackgroundSettings &backgroundSettings)
Sets the text's background settings.q.
QgsRectangle mapExtent() const
Returns the original extent of the map being rendered.
bool mergeLines
true if connected line features with identical label text should be merged prior to generating label ...
QgsGeometry centroid() const
Returns the center of mass of a geometry.
Color with alpha channel.
void setJoinStyle(Qt::PenJoinStyle style)
Sets the join style used for drawing the background shape.
QgsMapUnitScale repeatDistanceMapUnitScale
Map unit scale for repeating labels for a single feature.
MultiLineAlign multilineAlign
Horizontal alignment of multi-line labels.
virtual QgsAbstractGeometry * boundary() const =0
Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the...
void setMaximumNumberLabels(int number)
Sets the maximum number of labels which should be drawn for this layer.
static QPixmap labelSettingsPreviewPixmap(const QgsPalLayerSettings &settings, QSize size, const QString &previewText=QString(), int padding=0)
Returns a pixmap preview for label settings.
Qt::PenJoinStyle joinStyle() const
Returns the buffer join style.
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
QgsGeometry intersection(const QgsGeometry &geometry) const
Returns a geometry representing the points shared by this geometry and other.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Positive double value (including 0)
Container for settings relating to a text background object.
const QgsCoordinateReferenceSystem & crs
Percentage of another measurement (e.g., canvas size, feature size)
static int sizeToPixel(double size, const QgsRenderContext &c, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &mapUnitScale=QgsMapUnitScale())
Calculates pixel size (considering output size should be in pixel or map units, scale factors and opt...
void setBlurRadiusUnit(QgsUnitTypes::RenderUnit units)
Sets the units used for the shadow's blur radius.
QVector< PredefinedPointPosition > predefinedPositionOrder
Ordered list of predefined label positions for points.
SimplifyAlgorithm
Types of simplification algorithms that can be used.
int autoWrapLength
If non-zero, indicates that label text should be automatically wrapped to (ideally) the specified num...
QString parserErrorString() const
Returns parser error.
double maxCurvedCharAngleIn
Maximum angle between inside curved label characters (valid range 20.0 to 60.0).
QgsCoordinateTransform ct
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes takes output image size into accou...
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored)
static QString encodePoint(QPointF point)
Encodes a QPointF to a string.
bool reverseDirectionSymbol
True if direction symbols should be reversed.
Rotation (value between 0-360 degrees)
double maxScale
The maximum scale, or 0.0 if unset.
static Qt::PenJoinStyle decodePenJoinStyle(const QString &str)
Contains settings related to how the label engine treats features as obstacles.
ShapeType type() const
Returns the type of background shape (e.g., square, ellipse, SVG).
void setOffset(QPointF offset)
Sets the offset used for drawing the background shape.
void setFormat(const QgsTextFormat &format)
Sets the label text formatting settings, e.g., font settings, buffer settings, etc.
QgsCoordinateReferenceSystem destinationCrs() const
returns CRS of destination coordinate reference system
bool isActive(int key) const override
Returns true if the collection contains an active property with the specified key.
double zIndex
Z-Index of label, where labels with a higher z-index are rendered on top of labels with a lower z-ind...
double mapRotation() const
Returns current map rotation in degrees.
void setHasFixedPosition(bool enabled)
Sets whether the label should use a fixed position instead of being automatically placed...
QgsStringReplacementCollection substitutions
Substitution collection for automatic text substitution with labels.
Qt::PenJoinStyle joinStyle() const
Returns the buffer join style.
The QgsMapSettings class contains configuration for rendering of the map.
static QString encodeColor(const QColor &color)
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the buffer size.
static bool staticWillUseLayer(QgsVectorLayer *layer)
called to find out whether the layer is used for labeling
void writeXml(QDomElement &elem, QDomDocument &doc) const
Writes the collection state to an XML element.
static QSizeF toSize(const QVariant &value, bool *ok=nullptr)
Converts a value to a size.
QVariant value(int key, const QgsExpressionContext &context, const QVariant &defaultValue=QVariant()) const override
Returns the calculated value of the property with the specified key from within the collection...
QgsGeometry mergeLines() const
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line ...
Place direction symbols on left/right of label.
Perform transforms between map coordinates and device coordinates.
QgsPointXY transform(const QgsPointXY &p) const
Transform the point from map (world) coordinates to device coordinates.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
void setBlendMode(QPainter::CompositionMode mode)
Sets the blending mode used for drawing the background shape.
bool prepare(const QgsExpressionContext &context=QgsExpressionContext()) const override
Prepares the collection against a specified expression context.
Property
Data definable properties.
double cost() const
Returns the candidate label position's geographical cost.
static QString encodeTextOrientation(QgsTextFormat::TextOrientation orientation)
Encodes a text orientation.
No simplification can be applied.
QPointF toQPointF() const
Converts a point to a QPointF.
void setUseAdvancedEffects(bool enabled)
Used to enable or disable advanced effects such as blend modes.
bool displayAll
If true, all features will be labelled even when overlaps occur.
QColor color() const
Returns the color of the drop shadow.
T qgsEnumKeyToValue(const QString &key, const T &defaultValue)
Returns the value corresponding to the given key of an enum.
void setOffsetDistance(double distance)
Sets the distance for offsetting the position of the shadow from the text.
void setScaleFactor(double factor)
Sets the scaling factor for the render to convert painter units to physical sizes.
bool isGeosValid(QgsGeometry::ValidityFlags flags=nullptr) const
Checks validity of the geometry using GEOS.
static QgsTextFormat::TextOrientation decodeTextOrientation(const QString &name, bool *ok=nullptr)
Attempts to decode a string representation of a text orientation.
Text within rectangle draw mode.
static QString capitalize(const QString &string, Capitalization capitalization)
Converts a string by applying capitalization rules to the string.
QColor previewBackgroundColor() const
Returns the background color for text previews.
Offset distance applies from point geometry.
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
QList< QgsLabelPosition > labelsAtPosition(const QgsPointXY &p) const
Returns infos about labels at a given (map) position.
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
#define QgsDebugMsgLevel(str, level)
double tolerance() const
Gets the tolerance of simplification in map units. Represents the maximum distance in map units betwe...
TextOrientation orientation() const
Returns the orientation of the text.
double opacity() const
Returns the mask's opacity.
int fontMaxPixelSize
Maximum pixel size for showing rendered map unit labels (1 - 10000).
static bool fontFamilyOnSystem(const QString &family)
Check whether font family is on system in a quick manner, which does not compare [foundry].
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Write settings into a DOM element.
Maximum map scale (ie most "zoomed in")
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.
The geometries can be fully simplified by its BoundingBox.
void setBlendMode(QPainter::CompositionMode mode)
Sets the blending mode used for drawing the drop shadow.
Vertically oriented text.
double width() const
Returns the width of the rectangle.
void setActive(bool active)
Sets whether the property is currently active.
void setColor(const QColor &color)
Sets the color for the drop shadow.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setDataDefinedValues(const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &values)
Sets data-defined values.
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
void setEnabled(bool enabled)
Sets whether the text shadow will be drawn.
void setEnabled(bool enabled)
Sets whether the text buffer will be drawn.
Horizontal alignment for data defined label position (Left, Center, Right)
Arranges candidates in a circle around a point (or centroid of a polygon). Applies to point or polygo...
void setAnchorPosition(const QgsPointXY &anchorPosition)
In case of quadrand or aligned positioning, this is set to the anchor point.
const QgsMapToPixel * xform
Property requires a numeric value.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
void calculateInfo(bool curvedLabeling, QFontMetricsF *fm, const QgsMapToPixel *xform, double fontScale, double maxinangle, double maxoutangle)
calculate data for info(). setDefinedFont() must have been called already.
QgsPalLayerSettings & operator=(const QgsPalLayerSettings &s)
copy operator - only copies the permanent members
QString svgFile() const
Returns the absolute path to the background SVG file, if set.
Qt::PenJoinStyle joinStyle() const
Returns the join style used for drawing the background shape.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
QgsTextBackgroundSettings & background()
Returns a reference to the text background settings.
QgsTextBufferSettings & buffer()
Returns a reference to the text buffer settings.
Upside-down labels (90 <= angle < 270) are shown upright.
SizeType
Methods for determining the background shape size.
double opacity() const
Returns the buffer opacity.
OffsetType
Behavior modifier for label offset and distance, only applies in some label placement modes...
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
QgsTextMaskSettings & mask()
Returns a reference to the masking settings.
void updateDataDefinedProperties(const QgsPropertyCollection &properties, QgsExpressionContext &context)
Updates the obstacle settings to respect any data defined properties set within the specified propert...
static QPainter::CompositionMode decodeBlendMode(const QString &s)
void setRotatedSize(QSizeF size)
Sets an alternate label size to be used when a label rotation angle is between 45 to 135 and 235 to 3...
static QgsCallout * defaultCallout()
Create a new instance of a callout with default settings.
void removeCustomProperty(const QString &key)
Remove a custom property from layer.
static QgsTextShadowSettings::ShadowPlacement decodeShadowPlacementType(const QString &string)
Decodes a string representation of a shadow placement type to a type.
Label below point, slightly right of center.
void setSize(QSizeF size)
Sets the size of the background shape.
void clear() override
Removes all properties from the collection.
static Q_INVOKABLE QgsUnitTypes::RenderUnit decodeRenderUnit(const QString &string, bool *ok=nullptr)
Decodes a render unit from a string.
double mapUnitsPerPixel() const
Returns current map units per pixel.
A store for object properties.
virtual void startRender(QgsRenderContext &context)
Prepares the callout for rendering on the specified render context.
void setRadii(QSizeF radii)
Sets the radii used for rounding the corners of shapes.
double distance(double x, double y) const
Returns the distance between this point and a specified x, y coordinate.
Implementation of GeometrySimplifier using the "MapToPixel" algorithm.
Point geometry type, with support for z-dimension and m-values.
const QgsMapToPixel & mapToPixel() const
void setLimitNumberLabelsEnabled(bool enabled)
Sets whether the the number of labels drawn for the layer should be limited.
Double value (including negative values)
void setJoinStyle(Qt::PenJoinStyle style)
Sets the join style used for drawing the buffer.
Minimum map scale (ie most "zoomed out")
double minimumFeatureSize() const
Returns the minimum feature size (in millimeters) for a feature to be labelled.
Convert just the first letter of each word to uppercase, leave the rest untouched.
double length() const
Returns the planar, 2-dimensional length of geometry.
Convert all characters to uppercase.
Offset distance applies from rendered symbol bounds.
void setSizeType(SizeType type)
Sets the method used to determine the size of the background shape (e.g., fixed size or buffer around...
const QgsTextFormat & format() const
Returns the label text formatting settings, e.g., font settings, buffer settings, etc...
Definition for a property.
QList< QgsLabelPosition > labelsWithinRect(const QgsRectangle &r) const
Returns infos about labels within a given (map) rectangle.
Capitalization
Capitalization options.
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Write settings into a DOM element.
QMap< int, QgsPropertyDefinition > QgsPropertiesDefinition
Definition of available properties.
void setType(ShapeType type)
Sets the type of background shape to draw (e.g., square, ellipse, SVG).
Place direction symbols on above label.
static Q_INVOKABLE QString encodeUnit(QgsUnitTypes::DistanceUnit unit)
Encodes a distance unit to a string.
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.
static void drawText(const QRectF &rect, double rotation, HAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, bool drawAsOutlines=true)
Draws text within a rectangle using the specified settings.
QgsExpressionContext & expressionContext()
Gets the expression context.
QString asWkt(int precision=17) const
Exports the geometry to WKT.
Label rotation (deprecated, for old project compatibility only)
void setParameters(double mapUnitsPerPixel, double centerX, double centerY, int widthPixels, int heightPixels, double rotation)
Set parameters for use in transforming coordinates.
Q_DECL_DEPRECATED QColor previewBkgrdColor
double rotation() const
Returns the rotation for the background shape, in degrees clockwise.
bool plusSign
Whether '+' signs should be prepended to positive numeric labels.
double lineHeight() const
Returns the line height for text.
void setEnabled(bool enabled)
Sets whether the text background will be drawn.
unsigned int placementFlags
int offsetAngle() const
Returns the angle for offsetting the position of the shadow from the text.
QgsWkbTypes::GeometryType geometryGeneratorType
The type of the result geometry of the geometry generator.
ShapeType
Background shape types.
QString wrapChar
Wrapping character string.
bool valueAsBool(int key, const QgsExpressionContext &context, bool defaultValue=false, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as an boolean...
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Read settings from a DOM element.
void setFeature(const QgsFeature &feature)
Sets the original feature associated with this label.
#define Q_NOWARN_DEPRECATED_POP
Placement
Placement modes which determine how label candidates are generated for a feature. ...
static QString encodePredefinedPositionOrder(const QVector< QgsPalLayerSettings::PredefinedPointPosition > &positions)
Encodes an ordered list of predefined point label positions to a string.
QString rightDirectionSymbol
String to use for right direction arrows.
bool preserveRotation
True if label rotation should be preserved during label pin/unpin operations.
QString valueAsString(int key, const QgsExpressionContext &context, const QString &defaultString=QString(), bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a string...
QString lastError() const
Returns an error string referring to the last error encountered either when this geometry was created...
QgsGeometry simplify(double tolerance) const
Returns a simplified version of this geometry using a specified tolerance value.
QgsExpression * getLabelExpression()
Returns the QgsExpression for this label settings.
Arranges candidates parallel to a generalised line representing the feature or parallel to a polygon'...
This class contains information how to simplify geometries fetched from a vector layer.
QFont scaledFont(const QgsRenderContext &context) const
Returns a font with the size scaled to match the format's size settings (including units and map unit...
Contains information about the context of a rendering operation.
double convertToPainterUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to painter units (pixels).
bool enabled() const
Returns true if the the callout is enabled.
bool centroidWhole
true if feature centroid should be calculated from the whole feature, or false if only the visible pa...
bool scaleVisibility
Set to true to limit label visibility to a range of scales.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the size.
QgsUnitTypes::RenderUnit sizeUnit() const
Returns the units for the buffer size.
The QgsLabelFeature class describes a feature that should be used within the labeling engine...
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0)
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
void updateDataDefinedProperties(const QgsPropertyCollection &properties, QgsExpressionContext &context)
Updates the thinning settings to respect any data defined properties set within the specified propert...
const QgsFeature * mCurFeat
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
double getAlpha() const
Returns the angle to rotate text (in rad).
Points (e.g., for font sizes)
Property requires a string value.
bool enabled() const
Returns whether the shadow is enabled.
bool limitNumberOfLabelsEnabled() const
Returns true if the number of labels drawn for the layer should be limited.
Mixed case, ie no change.
QgsMapUnitScale distMapUnitScale
Map unit scale for label feature distance.
bool fitInPolygonOnly
true if only labels which completely fit within a polygon are allowed.
Container for settings relating to a text shadow.
QColor color() const
Returns the color of the buffer.
bool conflictsWithObstacle() const
Returns whether the position is marked as conflicting with an obstacle feature.
double getX(int i=0) const
Returns the down-left x coordinate.
double size() const
Returns the size of the buffer.
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
void setMapSettings(const QgsMapSettings &settings)
Sets the map settings associated with the labeling run.
Container for settings relating to a text buffer.
bool forceLocalOptimization() const
Gets where the simplification executes, after fetch the geometries from provider, or when supported...
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 setFillColor(const QColor &color)
Sets the color used for filing the background shape.
static bool updateFontViaStyle(QFont &f, const QString &fontstyle, bool fallback=false)
Updates font with named style and retain all font properties.
OffsetType offsetType
Offset type for layer (only applies in certain placement modes)
double dist
Distance from feature to the label.
Label on top of point, slightly right of center.
double size() const
Returns the size for rendered text.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
bool useSubstitutions
True if substitutions should be applied.
This class represents a coordinate reference system (CRS).
void setStrokeWidthUnit(QgsUnitTypes::RenderUnit units)
Sets the units used for the shape's stroke width.
bool enabled() const
Returns whether the background is enabled.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
void setObstacleSettings(const QgsLabelObstacleSettings &settings)
Sets the label's obstacle settings.
static QStringList splitToGraphemes(const QString &text)
Splits a text string to a list of graphemes, which are the smallest allowable character divisions in ...
SimplifyHints simplifyHints() const
Gets the simplification hints of the vector layer managed.
SizeType sizeType() const
Returns the method used to determine the size of the background shape (e.g., fixed size or buffer aro...
LabelPosition is a candidate feature label position.
bool enabled() const
Returns whether the buffer is enabled.
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.
void setBlendMode(QPainter::CompositionMode mode)
Sets the blending mode used for drawing the text.
void setBuffer(const QgsTextBufferSettings &bufferSettings)
Sets the text's buffer settings.
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
void startRender(QgsRenderContext &context)
Prepares the label settings for rendering.
bool hasActiveProperties() const override
Returns true if the collection has any active properties, or false if all properties within the colle...
QgsCallout * callout() const
Returns the label callout renderer, responsible for drawing label callouts.
Distance which labels can extend past either end of linear features.
Whether the mask is enabled.
bool isExpression
true if this label is made from a expression string, e.g., FieldName || 'mm'
Convert all characters to lowercase.
double overrunDistance
Distance which labels are allowed to overrun past the start or end of line features.
void setEnabled(bool)
Returns whether the mask is enabled.
void setShadow(const QgsTextShadowSettings &shadowSettings)
Sets the text's drop shadow settings.
QgsWkbTypes::GeometryType type
double factor() const
Returns the obstacle factor, where 1.0 = default, < 1.0 more likely to be covered by labels...
void readXml(const QDomElement &elem)
Reads the collection state from an XML element.
Custom exception class for Coordinate Reference System related exceptions.
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
QgsUnitTypes::RenderUnit overrunDistanceUnit
Units for label overrun distance.
static QVector< QgsPalLayerSettings::PredefinedPointPosition > decodePredefinedPositionOrder(const QString &positionString)
Decodes a string to an ordered list of predefined point label positions.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the shape size.
ObstacleType type() const
Returns how features act as obstacles for labels.
QString process(const QString &input) const
Processes a given input string, applying any valid replacements which should be made using QgsStringR...
static QString svgSymbolNameToPath(const QString &name, const QgsPathResolver &pathResolver)
Determines an SVG symbol's path from its name.
QgsPointXY center() const
Returns the center point of the rectangle.
double area() const
Returns the planar, 2-dimensional area of the geometry.
Y-coordinate data defined label position.
void setOpacity(double opacity)
Sets the mask's opacity.
void setCallout(QgsCallout *callout)
Sets the label callout renderer, responsible for drawing label callouts.
void setMinimumFeatureSize(double size)
Sets the minimum feature size (in millimeters) for a feature to be labelled.
Container for all settings relating to text rendering.
QgsUnitTypes::RenderUnit sizeUnit() const
Returns the units for the size of rendered text.
void setBlendMode(QPainter::CompositionMode mode)
Sets the blending mode used for drawing the buffer.
bool centroidInside
true if centroid positioned labels must be placed inside their corresponding feature polygon...
Max scale (deprecated, for old project compatibility only)
bool contains(const QgsPointXY *p) const
Returns true if the geometry contains the point p.
void setSvgFile(const QString &file)
Sets the path to the background SVG file.
void setSize(double size)
Sets the size of the buffer.
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.
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
double scaleFactor() const
Returns the scaling factor for the render to convert painter units to physical sizes.
Represents a vector layer which manages a vector based data sets.
Arranges candidates following the curvature of a polygon's boundary. Applies to polygon layers only...
double minScale
The minimum scale, or 0.0 if unset.
void setOpacity(double opacity)
Sets the buffer opacity.
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
virtual bool writeXml(QDomElement &collectionElem, const QgsPropertiesDefinition &definitions) const
Writes the current state of the property collection into an XML element.
QString updateDataDefinedString(const QString &value)
int valueAsInt(int key, const QgsExpressionContext &context, int defaultValue=0, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as an integer...
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
bool isObstacle() const
Returns true if the features are obstacles to labels of other layers.
int maximumNumberLabels() const
Returns the maximum number of labels which should be drawn for this layer.
Vertical alignment for data defined label position (Bottom, Base, Half, Cap, Top) ...
Whether all parts of multi-part features should be labeled.
static QgsGeometry collectGeometry(const QVector< QgsGeometry > &geometries)
Creates a new multipart geometry from a list of QgsGeometry objects.
void setSizeUnit(QgsUnitTypes::RenderUnit unit)
Sets the units used for the buffer size.
QString namedStyle() const
Returns the named style for the font used for rendering text (e.g., "bold").
QFont font() const
Returns the font used for rendering text.
void setRotationType(RotationType type)
Sets the method used for rotating the background shape.
bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames, const QgsFields &fields, const QgsMapSettings &mapSettings, const QgsCoordinateReferenceSystem &crs)
Prepare for registration of features.
int fontMinPixelSize
Minimum pixel size for showing rendered map unit labels (1 - 1000).
void setColor(const QColor &color)
Sets the color for the buffer.
int priority
Label priority.
QgsUnitTypes::RenderUnit sizeUnit() const
Returns the units used for the shape's size.
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
bool enabled() const
Returns whether the mask is enabled.
bool labelPerPart
true if every part of a multi-part feature should be labeled.
QgsUnitTypes::RenderUnit distUnits
Units the distance from feature to the label.
static QString encodePenJoinStyle(Qt::PenJoinStyle style)
void setType(ObstacleType type)
Controls how features act as obstacles for labels.
bool useMaxLineLengthForAutoWrap
If true, indicates that when auto wrapping label text the autoWrapLength length indicates the maximum...
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
double opacity() const
Returns the shadow's opacity.
Container for settings relating to a selective masking around a text.
QgsMapUnitScale labelOffsetMapUnitScale
Map unit scale for label offset.
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)...
QgsProperty property(int key) const override
Returns a matching property from the collection, if one exists.
2D size (width/height different)
The QgsMargins class defines the four margins of a rectangle.
void setOpacity(double opacity)
Sets the background shape's opacity.
RenderUnit
Rendering size units.
bool diagramsEnabled() const
Returns whether the layer contains diagrams which are enabled and should be drawn.
static QColor decodeColor(const QString &str)
Buffer transparency (deprecated)
QgsMarkerSymbol * markerSymbol() const
Returns the marker symbol to be rendered in the background.
double height() const
Returns the height of the rectangle.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label's property collection, used for data defined overrides.
Text transparency (deprecated)
static QString encodeLinePlacementFlags(QgsLabeling::LinePlacementFlags flags)
Encodes line placement flags to a string.
double minimumScale
The minimum map scale (i.e.
Horizontally oriented text.
void stopRender(QgsRenderContext &context)
Finalises the label settings after use.
QString fieldName
Name of field (or an expression) to use for label text.
bool fontLimitPixelSize
true if label sizes should be limited by pixel size.
DirectionSymbols placeDirectionSymbol
Placement option for direction symbols.
void setOffsetAngle(int angle)
Sets the angle for offsetting the position of the shadow from the text.
static QgsTextBackgroundSettings::ShapeType decodeShapeType(const QString &string)
Decodes a string representation of a background shape type to a type.
static double textHeight(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, DrawMode mode, QFontMetricsF *fontMetrics=nullptr)
Returns the height of a text based on a given format.
void readFromLayer(QgsVectorLayer *layer)
Reads settings from a layer's custom properties (for QGIS 2.x projects).
Color with no alpha channel.
QgsWkbTypes::GeometryType layerType
Geometry type of layers associated with these settings.
void setRotation(double rotation)
Sets the rotation for the background shape, in degrees clockwise.