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 const QString defaultFontString = settings.
value( u
"LayoutDesigner/defaultFont"_s, QVariant(),
QgsSettings::Gui ).toString();
58 if ( !defaultFontString.isEmpty() )
60 QFont f = mFormat.font();
66 mFormat.setSize( 10 );
79 refreshExpressionContext();
102 const double penWidth =
frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
103 const double xPenAdjust = mMarginX < 0 ? -penWidth : penWidth;
104 const double yPenAdjust = mMarginY < 0 ? -penWidth : penWidth;
110 painterRect = QRectF( ( xPenAdjust + mMarginX ) * rectScale,
111 ( yPenAdjust + mMarginY ) * rectScale,
112 ( rect().width() - 2 * xPenAdjust - 2 * mMarginX ) * rectScale,
113 ( rect().height() - 2 * yPenAdjust - 2 * mMarginY ) * rectScale );
118#if QT_VERSION >= QT_VERSION_CHECK( 6, 7, 0 )
119 constexpr double adjustmentFactor = 4.18;
121 constexpr double adjustmentFactor = 3.77;
125 painterRect = QRectF( 0, 0,
126 ( rect().width() ) * rectScale,
127 ( rect().height() - yPenAdjust - mMarginY ) * rectScale );
136 QTextDocument document;
137 document.setDocumentMargin( 0 );
139 document.setDefaultStyleSheet( createStylesheet() );
141 document.setDefaultFont( createDefaultFont() );
143 QTextOption textOption = document.defaultTextOption();
144 textOption.setAlignment( mHAlignment );
145 document.setDefaultTextOption( textOption );
147 document.setHtml( u
"<body>%1</body>"_s.arg(
currentText() ) );
148 document.drawContents( painter, painterRect );
168void QgsLayoutItemLabel::contentChanged()
193 mLayout->itemsModel()->updateItemDisplayName(
this );
207 if (
mLayout &&
id().isEmpty() )
210 mLayout->itemsModel()->updateItemDisplayName(
this );
214void QgsLayoutItemLabel::refreshExpressionContext()
223 mDistanceArea->setSourceCrs( layer->
crs(),
mLayout->project()->transformContext() );
230 mDistanceArea->setSourceCrs( referenceMap->
crs(),
mLayout->project()->transformContext() );
232 mDistanceArea->setEllipsoid(
mLayout->project()->ellipsoid() );
238void QgsLayoutItemLabel::updateBoundingRect()
240 QRectF rectangle = rect();
241 const double frameExtension =
frameEnabled() ? pen().widthF() / 2.0 : 0.0;
242 if ( frameExtension > 0 )
243 rectangle.adjust( -frameExtension, -frameExtension, frameExtension, frameExtension );
247 rectangle.adjust( mMarginX, 0, -mMarginX, 0 );
251 rectangle.adjust( 0, mMarginY, 0, -mMarginY );
254 if ( rectangle != mCurrentRectangle )
256 prepareGeometryChange();
257 mCurrentRectangle = rectangle;
264 QString displayText = mText;
265 replaceDateText( displayText );
272void QgsLayoutItemLabel::replaceDateText( QString &text )
const
274 const QString constant = u
"$CURRENT_DATE"_s;
275 const int currentDatePos =
text.indexOf( constant );
276 if ( currentDatePos != -1 )
280 const int openingBracketPos =
text.indexOf(
'(', currentDatePos );
281 const int closingBracketPos =
text.indexOf(
')', openingBracketPos + 1 );
282 if ( openingBracketPos != -1 &&
283 closingBracketPos != -1 &&
284 ( closingBracketPos - openingBracketPos ) > 1 &&
285 openingBracketPos == currentDatePos + constant.size() )
287 formatText =
text.mid( openingBracketPos + 1, closingBracketPos - openingBracketPos - 1 );
288 text.replace( currentDatePos, closingBracketPos - currentDatePos + 1, QDate::currentDate().toString( formatText ) );
292 text.replace(
"$CURRENT_DATE"_L1, QDate::currentDate().toString() );
299 mFormat.setFont( f );
300 if ( f.pointSizeF() > 0 )
301 mFormat.setSize( f.pointSizeF() );
320 updateBoundingRect();
326 updateBoundingRect();
332 updateBoundingRect();
343 itemShiftAdjustSize( newSize.width(), newSize.height(), xShift, yShift );
346 attemptSetSceneRect( QRectF( pos().x() + xShift, pos().y() + yShift, newSize.width(), newSize.height() ) );
352 const double newWidth = newSize.width();
353 const double newHeight = newSize.height();
354 const double currentWidth = rect().width();
355 const double currentHeight = rect().height();
367 xShift = - ( newWidth - currentWidth ) / 2.0;
372 xShift = - ( newWidth - currentWidth );
378 yShift = -( newHeight - currentHeight ) / 2.0;
382 xShift = - ( newWidth - currentWidth ) / 2.0;
383 yShift = -( newHeight - currentHeight ) / 2.0;
387 xShift = - ( newWidth - currentWidth );
388 yShift = -( newHeight - currentHeight ) / 2.0;
393 yShift = - ( newHeight - currentHeight );
397 xShift = - ( newWidth - currentWidth ) / 2.0;
398 yShift = - ( newHeight - currentHeight );
402 xShift = - ( newWidth - currentWidth );
403 yShift = - ( newHeight - currentHeight );
408 attemptSetSceneRect( QRectF( pos().x() + xShift, pos().y() + yShift, newSize.width(), newSize.height() ) );
416 const QStringList lines =
currentText().split(
'\n' );
420 const double penWidth =
frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
422 const double width = textWidth + 2 * mMarginX + 2 * penWidth;
423 const double height = fontHeight + 2 * mMarginY + 2 * penWidth;
430 return mFormat.font();
435 layoutLabelElem.setAttribute( u
"htmlState"_s,
static_cast< int >( mMode ) );
437 layoutLabelElem.setAttribute( u
"labelText"_s, mText );
438 layoutLabelElem.setAttribute( u
"marginX"_s, QString::number( mMarginX ) );
439 layoutLabelElem.setAttribute( u
"marginY"_s, QString::number( mMarginY ) );
440 layoutLabelElem.setAttribute( u
"halign"_s, mHAlignment );
441 layoutLabelElem.setAttribute( u
"valign"_s, mVAlignment );
443 QDomElement textElem = mFormat.writeXml( doc, rwContext );
444 layoutLabelElem.appendChild( textElem );
454 mText = itemElem.attribute( u
"labelText"_s );
457 mMode =
static_cast< Mode >( itemElem.attribute( u
"htmlState"_s ).toInt() );
460 bool marginXOk =
false;
461 bool marginYOk =
false;
462 mMarginX = itemElem.attribute( u
"marginX"_s ).toDouble( &marginXOk );
463 mMarginY = itemElem.attribute( u
"marginY"_s ).toDouble( &marginYOk );
464 if ( !marginXOk || !marginYOk )
467 const double margin = itemElem.attribute( u
"margin"_s, u
"1.0"_s ).toDouble();
473 mHAlignment =
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( u
"halign"_s ).toInt() );
476 mVAlignment =
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( u
"valign"_s ).toInt() );
479 QDomNodeList textFormatNodeList = itemElem.elementsByTagName( u
"text-style"_s );
480 if ( !textFormatNodeList.isEmpty() )
482 QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
483 mFormat.readXml( textFormatElem, context );
490 f.fromString( itemElem.attribute( u
"font"_s, QString() ) );
492 mFormat.setFont( f );
493 if ( f.pointSizeF() > 0 )
495 mFormat.setSize( f.pointSizeF() );
498 else if ( f.pixelSize() > 0 )
500 mFormat.setSize( f.pixelSize() );
505 const QDomNodeList fontColorList = itemElem.elementsByTagName( u
"FontColor"_s );
506 if ( !fontColorList.isEmpty() )
508 const QDomElement fontColorElem = fontColorList.at( 0 ).toElement();
509 const int red = fontColorElem.attribute( u
"red"_s, u
"0"_s ).toInt();
510 const int green = fontColorElem.attribute( u
"green"_s, u
"0"_s ).toInt();
511 const int blue = fontColorElem.attribute( u
"blue"_s, u
"0"_s ).toInt();
512 const int alpha = fontColorElem.attribute( u
"alpha"_s, u
"255"_s ).toInt();
513 mFormat.setColor( QColor( red, green, blue, alpha ) );
515 else if ( textFormatNodeList.isEmpty() )
517 mFormat.setColor( QColor( 0, 0, 0 ) );
521 updateBoundingRect();
528 if ( !
id().isEmpty() )
536 return tr(
"<HTML Label>" );
542 const QString
text = mText;
543 if (
text.isEmpty() )
545 return tr(
"<Label>" );
547 if (
text.length() > 25 )
549 return QString( tr(
"%1…" ) ).arg(
text.left( 25 ).simplified() );
553 return text.simplified();
562 return mCurrentRectangle;
568 updateBoundingRect();
574 updateBoundingRect();
581 refreshExpressionContext();
587 if ( evaluated == mText )
593void QgsLayoutItemLabel::itemShiftAdjustSize(
double newWidth,
double newHeight,
double &xShift,
double &yShift )
const
596 const double currentWidth = rect().width();
597 const double currentHeight = rect().height();
601 const double r = rotation();
602 if ( r >= 0 && r < 90 )
604 if ( mHAlignment == Qt::AlignHCenter )
606 xShift = - ( newWidth - currentWidth ) / 2.0;
608 else if ( mHAlignment == Qt::AlignRight )
610 xShift = - ( newWidth - currentWidth );
612 if ( mVAlignment == Qt::AlignVCenter )
614 yShift = -( newHeight - currentHeight ) / 2.0;
616 else if ( mVAlignment == Qt::AlignBottom )
618 yShift = - ( newHeight - currentHeight );
621 if ( r >= 90 && r < 180 )
623 if ( mHAlignment == Qt::AlignHCenter )
625 yShift = -( newHeight - currentHeight ) / 2.0;
627 else if ( mHAlignment == Qt::AlignRight )
629 yShift = -( newHeight - currentHeight );
631 if ( mVAlignment == Qt::AlignTop )
633 xShift = -( newWidth - currentWidth );
635 else if ( mVAlignment == Qt::AlignVCenter )
637 xShift = -( newWidth - currentWidth / 2.0 );
640 else if ( r >= 180 && r < 270 )
642 if ( mHAlignment == Qt::AlignHCenter )
644 xShift = -( newWidth - currentWidth ) / 2.0;
646 else if ( mHAlignment == Qt::AlignLeft )
648 xShift = -( newWidth - currentWidth );
650 if ( mVAlignment == Qt::AlignVCenter )
652 yShift = ( newHeight - currentHeight ) / 2.0;
654 else if ( mVAlignment == Qt::AlignTop )
656 yShift = ( newHeight - currentHeight );
659 else if ( r >= 270 && r < 360 )
661 if ( mHAlignment == Qt::AlignHCenter )
663 yShift = -( newHeight - currentHeight ) / 2.0;
665 else if ( mHAlignment == Qt::AlignLeft )
667 yShift = -( newHeight - currentHeight );
669 if ( mVAlignment == Qt::AlignBottom )
671 xShift = -( newWidth - currentWidth );
673 else if ( mVAlignment == Qt::AlignVCenter )
675 xShift = -( newWidth - currentWidth / 2.0 );
680QFont QgsLayoutItemLabel::createDefaultFont()
const
682 QFont f = mFormat.font();
683 switch ( mFormat.sizeUnit() )
686 f.setPointSizeF( mFormat.size() / 0.352778 );
689 f.setPixelSize( mFormat.size() );
692 f.setPointSizeF( mFormat.size() );
695 f.setPointSizeF( mFormat.size() * 72 );
706double QgsLayoutItemLabel::htmlUnitsToLayoutUnits()
717QString QgsLayoutItemLabel::createStylesheet()
const
721 stylesheet += u
"body { margin: %1 %2;"_s.arg( std::max( mMarginY * mHtmlUnitsToLayoutUnits, 0.0 ) ).arg( std::max( mMarginX * mHtmlUnitsToLayoutUnits, 0.0 ) );
722 stylesheet += mFormat.asCSS( 0.352778 * mHtmlUnitsToLayoutUnits );
723 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 );
728QUrl QgsLayoutItemLabel::createStylesheetUrl()
const
731 ba.append( createStylesheet().toUtf8() );
732 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.
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.
Stores settings for use within QGIS.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
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.