38#include <QCoreApplication>
43#include <QTextDocument>
45#include "moc_qgslayoutitemlabel.cpp"
47using namespace Qt::StringLiterals;
52 mDistanceArea = std::make_unique<QgsDistanceArea>();
53 mHtmlUnitsToLayoutUnits = htmlUnitsToLayoutUnits();
57 if ( !defaultFontString.isEmpty() )
59 QFont f = mFormat.font();
65 mFormat.setSize( 10 );
75 refreshExpressionContext();
98 const double penWidth =
frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
99 const double xPenAdjust = mMarginX < 0 ? -penWidth : penWidth;
100 const double yPenAdjust = mMarginY < 0 ? -penWidth : penWidth;
107 = QRectF( ( xPenAdjust + mMarginX ) * rectScale, ( yPenAdjust + mMarginY ) * rectScale, ( rect().width() - 2 * xPenAdjust - 2 * mMarginX ) * rectScale, ( rect().height() - 2 * yPenAdjust - 2 * mMarginY ) * rectScale );
112#if QT_VERSION >= QT_VERSION_CHECK( 6, 7, 0 )
113 constexpr double adjustmentFactor = 4.18;
115 constexpr double adjustmentFactor = 3.77;
119 painterRect = QRectF( 0, 0, ( rect().width() ) * rectScale, ( rect().height() - yPenAdjust - mMarginY ) * rectScale );
128 QTextDocument document;
129 document.setDocumentMargin( 0 );
131 document.setDefaultStyleSheet( createStylesheet() );
133 document.setDefaultFont( createDefaultFont() );
135 QTextOption textOption = document.defaultTextOption();
136 textOption.setAlignment( mHAlignment );
137 document.setDefaultTextOption( textOption );
139 document.setHtml( u
"<body>%1</body>"_s.arg(
currentText() ) );
140 document.drawContents( painter, painterRect );
154void QgsLayoutItemLabel::contentChanged()
179 mLayout->itemsModel()->updateItemDisplayName(
this );
193 if (
mLayout &&
id().isEmpty() )
196 mLayout->itemsModel()->updateItemDisplayName(
this );
200void QgsLayoutItemLabel::refreshExpressionContext()
209 mDistanceArea->setSourceCrs( layer->
crs(),
mLayout->project()->transformContext() );
216 mDistanceArea->setSourceCrs( referenceMap->
crs(),
mLayout->project()->transformContext() );
218 mDistanceArea->setEllipsoid(
mLayout->project()->ellipsoid() );
224void QgsLayoutItemLabel::updateBoundingRect()
226 QRectF rectangle = rect();
227 const double frameExtension =
frameEnabled() ? pen().widthF() / 2.0 : 0.0;
228 if ( frameExtension > 0 )
229 rectangle.adjust( -frameExtension, -frameExtension, frameExtension, frameExtension );
233 rectangle.adjust( mMarginX, 0, -mMarginX, 0 );
237 rectangle.adjust( 0, mMarginY, 0, -mMarginY );
240 if ( rectangle != mCurrentRectangle )
242 prepareGeometryChange();
243 mCurrentRectangle = rectangle;
250 QString displayText = mText;
251 replaceDateText( displayText );
258void QgsLayoutItemLabel::replaceDateText( QString &text )
const
260 const QString constant = u
"$CURRENT_DATE"_s;
261 const int currentDatePos =
text.indexOf( constant );
262 if ( currentDatePos != -1 )
266 const int openingBracketPos =
text.indexOf(
'(', currentDatePos );
267 const int closingBracketPos =
text.indexOf(
')', openingBracketPos + 1 );
268 if ( openingBracketPos != -1 && closingBracketPos != -1 && ( closingBracketPos - openingBracketPos ) > 1 && openingBracketPos == currentDatePos + constant.size() )
270 formatText =
text.mid( openingBracketPos + 1, closingBracketPos - openingBracketPos - 1 );
271 text.replace( currentDatePos, closingBracketPos - currentDatePos + 1, QDate::currentDate().toString( formatText ) );
275 text.replace(
"$CURRENT_DATE"_L1, QDate::currentDate().toString() );
282 mFormat.setFont( f );
283 if ( f.pointSizeF() > 0 )
284 mFormat.setSize( f.pointSizeF() );
303 updateBoundingRect();
309 updateBoundingRect();
315 updateBoundingRect();
326 itemShiftAdjustSize( newSize.width(), newSize.height(), xShift, yShift );
329 attemptSetSceneRect( QRectF( pos().x() + xShift, pos().y() + yShift, newSize.width(), newSize.height() ) );
335 const double newWidth = newSize.width();
336 const double newHeight = newSize.height();
337 const double currentWidth = rect().width();
338 const double currentHeight = rect().height();
350 xShift = -( newWidth - currentWidth ) / 2.0;
355 xShift = -( newWidth - currentWidth );
361 yShift = -( newHeight - currentHeight ) / 2.0;
365 xShift = -( newWidth - currentWidth ) / 2.0;
366 yShift = -( newHeight - currentHeight ) / 2.0;
370 xShift = -( newWidth - currentWidth );
371 yShift = -( newHeight - currentHeight ) / 2.0;
376 yShift = -( newHeight - currentHeight );
380 xShift = -( newWidth - currentWidth ) / 2.0;
381 yShift = -( newHeight - currentHeight );
385 xShift = -( newWidth - currentWidth );
386 yShift = -( newHeight - currentHeight );
391 attemptSetSceneRect( QRectF( pos().x() + xShift, pos().y() + yShift, newSize.width(), newSize.height() ) );
399 const QStringList lines =
currentText().split(
'\n' );
403 const double penWidth =
frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
405 const double width = textWidth + 2 * mMarginX + 2 * penWidth;
406 const double height = fontHeight + 2 * mMarginY + 2 * penWidth;
413 return mFormat.font();
418 layoutLabelElem.setAttribute( u
"htmlState"_s,
static_cast< int >( mMode ) );
420 layoutLabelElem.setAttribute( u
"labelText"_s, mText );
421 layoutLabelElem.setAttribute( u
"marginX"_s, QString::number( mMarginX ) );
422 layoutLabelElem.setAttribute( u
"marginY"_s, QString::number( mMarginY ) );
423 layoutLabelElem.setAttribute( u
"halign"_s, mHAlignment );
424 layoutLabelElem.setAttribute( u
"valign"_s, mVAlignment );
426 QDomElement textElem = mFormat.writeXml( doc, rwContext );
427 layoutLabelElem.appendChild( textElem );
437 mText = itemElem.attribute( u
"labelText"_s );
440 mMode =
static_cast< Mode >( itemElem.attribute( u
"htmlState"_s ).toInt() );
443 bool marginXOk =
false;
444 bool marginYOk =
false;
445 mMarginX = itemElem.attribute( u
"marginX"_s ).toDouble( &marginXOk );
446 mMarginY = itemElem.attribute( u
"marginY"_s ).toDouble( &marginYOk );
447 if ( !marginXOk || !marginYOk )
450 const double margin = itemElem.attribute( u
"margin"_s, u
"1.0"_s ).toDouble();
456 mHAlignment =
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( u
"halign"_s ).toInt() );
459 mVAlignment =
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( u
"valign"_s ).toInt() );
462 QDomNodeList textFormatNodeList = itemElem.elementsByTagName( u
"text-style"_s );
463 if ( !textFormatNodeList.isEmpty() )
465 QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
466 mFormat.readXml( textFormatElem, context );
473 f.fromString( itemElem.attribute( u
"font"_s, QString() ) );
475 mFormat.setFont( f );
476 if ( f.pointSizeF() > 0 )
478 mFormat.setSize( f.pointSizeF() );
481 else if ( f.pixelSize() > 0 )
483 mFormat.setSize( f.pixelSize() );
488 const QDomNodeList fontColorList = itemElem.elementsByTagName( u
"FontColor"_s );
489 if ( !fontColorList.isEmpty() )
491 const QDomElement fontColorElem = fontColorList.at( 0 ).toElement();
492 const int red = fontColorElem.attribute( u
"red"_s, u
"0"_s ).toInt();
493 const int green = fontColorElem.attribute( u
"green"_s, u
"0"_s ).toInt();
494 const int blue = fontColorElem.attribute( u
"blue"_s, u
"0"_s ).toInt();
495 const int alpha = fontColorElem.attribute( u
"alpha"_s, u
"255"_s ).toInt();
496 mFormat.setColor( QColor( red, green, blue, alpha ) );
498 else if ( textFormatNodeList.isEmpty() )
500 mFormat.setColor( QColor( 0, 0, 0 ) );
504 updateBoundingRect();
511 if ( !
id().isEmpty() )
519 return tr(
"<HTML Label>" );
524 const QString
text = mText;
525 if (
text.isEmpty() )
527 return tr(
"<Label>" );
529 if (
text.length() > 25 )
531 return QString( tr(
"%1…" ) ).arg(
text.left( 25 ).simplified() );
535 return text.simplified();
544 return mCurrentRectangle;
550 updateBoundingRect();
556 updateBoundingRect();
563 refreshExpressionContext();
569 if ( evaluated == mText )
575void QgsLayoutItemLabel::itemShiftAdjustSize(
double newWidth,
double newHeight,
double &xShift,
double &yShift )
const
578 const double currentWidth = rect().width();
579 const double currentHeight = rect().height();
583 const double r = rotation();
584 if ( r >= 0 && r < 90 )
586 if ( mHAlignment == Qt::AlignHCenter )
588 xShift = -( newWidth - currentWidth ) / 2.0;
590 else if ( mHAlignment == Qt::AlignRight )
592 xShift = -( newWidth - currentWidth );
594 if ( mVAlignment == Qt::AlignVCenter )
596 yShift = -( newHeight - currentHeight ) / 2.0;
598 else if ( mVAlignment == Qt::AlignBottom )
600 yShift = -( newHeight - currentHeight );
603 if ( r >= 90 && r < 180 )
605 if ( mHAlignment == Qt::AlignHCenter )
607 yShift = -( newHeight - currentHeight ) / 2.0;
609 else if ( mHAlignment == Qt::AlignRight )
611 yShift = -( newHeight - currentHeight );
613 if ( mVAlignment == Qt::AlignTop )
615 xShift = -( newWidth - currentWidth );
617 else if ( mVAlignment == Qt::AlignVCenter )
619 xShift = -( newWidth - currentWidth / 2.0 );
622 else if ( r >= 180 && r < 270 )
624 if ( mHAlignment == Qt::AlignHCenter )
626 xShift = -( newWidth - currentWidth ) / 2.0;
628 else if ( mHAlignment == Qt::AlignLeft )
630 xShift = -( newWidth - currentWidth );
632 if ( mVAlignment == Qt::AlignVCenter )
634 yShift = ( newHeight - currentHeight ) / 2.0;
636 else if ( mVAlignment == Qt::AlignTop )
638 yShift = ( newHeight - currentHeight );
641 else if ( r >= 270 && r < 360 )
643 if ( mHAlignment == Qt::AlignHCenter )
645 yShift = -( newHeight - currentHeight ) / 2.0;
647 else if ( mHAlignment == Qt::AlignLeft )
649 yShift = -( newHeight - currentHeight );
651 if ( mVAlignment == Qt::AlignBottom )
653 xShift = -( newWidth - currentWidth );
655 else if ( mVAlignment == Qt::AlignVCenter )
657 xShift = -( newWidth - currentWidth / 2.0 );
662QFont QgsLayoutItemLabel::createDefaultFont()
const
664 QFont f = mFormat.font();
665 switch ( mFormat.sizeUnit() )
668 f.setPointSizeF( mFormat.size() / 0.352778 );
671 f.setPixelSize( mFormat.size() );
674 f.setPointSizeF( mFormat.size() );
677 f.setPointSizeF( mFormat.size() * 72 );
688double QgsLayoutItemLabel::htmlUnitsToLayoutUnits()
699QString QgsLayoutItemLabel::createStylesheet()
const
703 stylesheet += u
"body { margin: %1 %2;"_s.arg( std::max( mMarginY * mHtmlUnitsToLayoutUnits, 0.0 ) ).arg( std::max( mMarginX * mHtmlUnitsToLayoutUnits, 0.0 ) );
704 stylesheet += mFormat.asCSS( 0.352778 * mHtmlUnitsToLayoutUnits );
705 stylesheet += u
"text-align: %1; }"_s.arg( mHAlignment == Qt::AlignLeft ? u
"left"_s : mHAlignment == Qt::AlignRight ? u
"right"_s : mHAlignment == Qt::AlignHCenter ? u
"center"_s : u
"justify"_s );
710QUrl QgsLayoutItemLabel::createStylesheetUrl()
const
713 ba.append( createStylesheet().toUtf8() );
714 QUrl cssFileURL = QUrl( QString(
"data:text/css;charset=utf-8;base64," + ba.toBase64() ) );
@ Millimeters
Millimeters.
@ Percentage
Percentage of another measurement (e.g., canvas size, feature size).
@ Millimeters
Millimeters.
@ Points
Points (e.g., for font sizes).
@ Unknown
Mixed or unknown units.
@ MetersInMapUnits
Meters value as Map units.
@ ApplyScalingWorkaroundForTextRendering
Whether a scaling workaround designed to stablise the rendering of small font sizes (or for painters ...
@ WrapLines
Automatically wrap long lines of text.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
static QString replaceExpressionText(const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea=nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluat...
static bool setFromXmlChildNode(QFont &font, const QDomElement &element, const QString &childNode)
Sets the properties of a font to match the properties stored in an XML child node.
static void setFontFamily(QFont &font, const QString &family)
Sets the family for a font object.
Mode mode() const
Returns the label's current mode.
void setMarginX(double margin)
Sets the horizontal margin between the edge of the frame and the label contents, in layout units.
void setFrameEnabled(bool drawFrame) override
Sets whether this item has a frame drawn around it or not.
QRectF boundingRect() const override
QSizeF sizeForText() const
Returns the required item size (in layout units) for the label's text to fill the item.
void setMargin(double margin)
Sets the margin between the edge of the frame and the label contents.
int type() const override
static QgsLayoutItemLabel * create(QgsLayout *layout)
Returns a new label item for the specified layout.
bool readPropertiesFromElement(const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context) override
Sets item state from a DOM element.
Q_DECL_DEPRECATED QFont font() const
Returns the label's current font.
QgsLayoutItemLabel(QgsLayout *layout)
Constructor for QgsLayoutItemLabel, with the specified parent layout.
void setText(const QString &text)
Sets the label's preset text.
void setFrameStrokeWidth(QgsLayoutMeasurement strokeWidth) override
Sets the frame stroke width.
void setMarginY(double margin)
Sets the vertical margin between the edge of the frame and the label contents, in layout units.
void draw(QgsLayoutItemRenderContext &context) override
Draws the item's contents using the specified item render context.
Q_DECL_DEPRECATED void setFont(const QFont &font)
Sets the label's current font.
bool writePropertiesToElement(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const override
Stores item state within an XML DOM element.
void setMode(Mode mode)
Sets the label's current mode, allowing the label to switch between font based and HTML based renderi...
QString displayName() const override
Gets item display name.
QString text() const
Returns the label's preset text.
void convertToStaticText()
Converts the label's text() to a static string, by evaluating any expressions included in the text an...
QgsTextFormat textFormat() const
Returns the text format used for drawing text in the label.
void setTextFormat(const QgsTextFormat &format)
Sets the text format used for drawing text in the label.
QString currentText() const
Returns the text as it appears on the label (with evaluated expressions and other dynamic content).
QIcon icon() const override
Returns the item's icon.
void adjustSizeToText()
Resizes the item so that the label's text fits to the item.
@ ModeHtml
Label displays rendered HTML content.
@ ModeFont
Label displays text rendered using a single font.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
Contains settings and helpers relating to a render of a QgsLayoutItem.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
virtual void drawFrame(QgsRenderContext &context)
Draws the frame around the item.
virtual void setFrameStrokeWidth(QgsLayoutMeasurement width)
Sets the frame stroke width.
QgsLayoutItem(QgsLayout *layout, bool manageZValue=true)
Constructor for QgsLayoutItem, with the specified parent layout.
ReferencePoint referencePoint() const
Returns the reference point for positioning of the layout item.
ReferencePoint
Fixed position reference point.
@ LowerMiddle
Lower center of item.
@ MiddleLeft
Middle left of item.
@ UpperRight
Upper right corner of item.
@ LowerLeft
Lower left corner of item.
@ UpperLeft
Upper left corner of item.
@ UpperMiddle
Upper center of item.
@ MiddleRight
Middle right of item.
@ LowerRight
Lower right corner of item.
friend class QgsLayoutItemMap
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
virtual void setFrameEnabled(bool drawFrame)
Sets whether this item has a frame drawn around it or not.
void sizePositionChanged()
Emitted when the item's size or position changes.
virtual void invalidateCache()
Forces a deferred update of any cached image the item uses.
QString id() const
Returns the item's ID name.
bool frameEnabled() const
Returns true if the item includes a frame.
void refresh() override
Refreshes the item, causing a recalculation of any property overrides and recalculation of its positi...
void attemptSetSceneRect(const QRectF &rect, bool includesFrame=false)
Attempts to update the item's position and size to match the passed rect in layout coordinates.
void setBackgroundEnabled(bool drawBackground)
Sets whether this item has a background drawn under it or not.
Provides a method of storing measurements for use in QGIS layouts using a variety of different measur...
const QgsLayout * layout() const
Returns the layout the object is attached to.
void changed()
Emitted when the object's properties change.
QPointer< QgsLayout > mLayout
Provides a method of storing sizes, consisting of a width and height, for use in QGIS layouts.
static QgsRenderContext createRenderContextForLayout(QgsLayout *layout, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout and painter destination.
static const QgsSettingsEntryString * settingsLayoutDefaultFont
Settings entry for the default font family used for new layout items.
QgsCoordinateReferenceSystem crs
A container for the context for various read/write operations on objects.
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 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).
QPainter * painter()
Returns the destination QPainter for the render operation.
void setFlag(Qgis::RenderContextFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
Scoped object for saving and restoring a QPainter object's state.
Container for all settings relating to text rendering.
static Qgis::TextVerticalAlignment convertQtVAlignment(Qt::Alignment alignment)
Converts a Qt vertical alignment flag to a Qgis::TextVerticalAlignment value.
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 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.
static Qgis::TextHorizontalAlignment convertQtHAlignment(Qt::Alignment alignment)
Converts a Qt horizontal alignment flag to a Qgis::TextHorizontalAlignment value.
Represents a vector layer which manages a vector based dataset.