39#include <QCoreApplication>
51 mHtmlUnitsToLayoutUnits = htmlUnitsToLayoutUnits();
55 const QString defaultFontString = settings.
value( QStringLiteral(
"LayoutDesigner/defaultFont" ), QVariant(),
QgsSettings::Gui ).toString();
56 if ( !defaultFontString.isEmpty() )
58 QFont f = mFormat.
font();
59 f.setFamily( defaultFontString );
72 refreshExpressionContext();
75 if ( QThread::currentThread() == QApplication::instance()->thread() )
85 mWebPage->setIdentifier( tr(
"Layout label item" ) );
89 QPalette palette = mWebPage->palette();
90 palette.setBrush( QPalette::Base, Qt::transparent );
91 mWebPage->setPalette( palette );
93 mWebPage->mainFrame()->setZoomFactor( 10.0 );
94 mWebPage->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff );
95 mWebPage->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff );
97 connect( mWebPage.get(), &QWebPage::loadFinished,
this, &QgsLayoutItemLabel::loadingHtmlFinished );
121 double rectScale = 1.0;
132 const double penWidth =
frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
133 const double xPenAdjust = mMarginX < 0 ? -penWidth : penWidth;
134 const double yPenAdjust = mMarginY < 0 ? -penWidth : penWidth;
135 const QRectF painterRect( ( xPenAdjust + mMarginX ) * rectScale,
136 ( yPenAdjust + mMarginY ) * rectScale,
137 ( rect().width() - 2 * xPenAdjust - 2 * mMarginX ) * rectScale,
138 ( rect().height() - 2 * yPenAdjust - 2 * mMarginY ) * rectScale );
147 mFirstRender =
false;
152 painter->scale( 1.0 / mHtmlUnitsToLayoutUnits / 10.0, 1.0 / mHtmlUnitsToLayoutUnits / 10.0 );
153 mWebPage->setViewportSize( QSize( painterRect.width() * mHtmlUnitsToLayoutUnits * 10.0, painterRect.height() * mHtmlUnitsToLayoutUnits * 10.0 ) );
154 mWebPage->settings()->setUserStyleSheetUrl( createStylesheetUrl() );
155 mWebPage->mainFrame()->render( painter );
176void QgsLayoutItemLabel::contentChanged()
194 const QUrl baseUrl = QUrl::fromLocalFile(
mLayout->project()->absoluteFilePath() );
195 mWebPage->mainFrame()->setHtml( textToDraw, baseUrl );
203 if ( !mHtmlLoaded && ( !
mLayout || !
mLayout->renderContext().isPreviewRender() ) )
209 connect( mWebPage.get(), &QWebPage::loadFinished, &loop, &QEventLoop::quit );
213 timeoutTimer.setSingleShot(
true );
214 connect( &timeoutTimer, &QTimer::timeout, &loop, &QEventLoop::quit );
215 timeoutTimer.start( 20000 );
218 loop.exec( QEventLoop::ExcludeUserInputEvents );
228void QgsLayoutItemLabel::loadingHtmlFinished(
bool result )
236double QgsLayoutItemLabel::htmlUnitsToLayoutUnits()
257 mLayout->itemsModel()->updateItemDisplayName(
this );
271 if (
mLayout &&
id().isEmpty() )
274 mLayout->itemsModel()->updateItemDisplayName(
this );
278void QgsLayoutItemLabel::refreshExpressionContext()
287 mDistanceArea->setSourceCrs( layer->
crs(),
mLayout->project()->transformContext() );
294 mDistanceArea->setSourceCrs( referenceMap->
crs(),
mLayout->project()->transformContext() );
296 mDistanceArea->setEllipsoid(
mLayout->project()->ellipsoid() );
304 QString displayText = mText;
305 replaceDateText( displayText );
312void QgsLayoutItemLabel::replaceDateText( QString &text )
const
314 const QString constant = QStringLiteral(
"$CURRENT_DATE" );
315 const int currentDatePos =
text.indexOf( constant );
316 if ( currentDatePos != -1 )
320 const int openingBracketPos =
text.indexOf(
'(', currentDatePos );
321 const int closingBracketPos =
text.indexOf(
')', openingBracketPos + 1 );
322 if ( openingBracketPos != -1 &&
323 closingBracketPos != -1 &&
324 ( closingBracketPos - openingBracketPos ) > 1 &&
325 openingBracketPos == currentDatePos + constant.size() )
327 formatText =
text.mid( openingBracketPos + 1, closingBracketPos - openingBracketPos - 1 );
328 text.replace( currentDatePos, closingBracketPos - currentDatePos + 1, QDate::currentDate().toString( formatText ) );
332 text.replace( QLatin1String(
"$CURRENT_DATE" ), QDate::currentDate().toString() );
340 if ( f.pointSizeF() > 0 )
341 mFormat.
setSize( f.pointSizeF() );
358 prepareGeometryChange();
364 prepareGeometryChange();
370 prepareGeometryChange();
381 itemShiftAdjustSize( newSize.width(), newSize.height(), xShift, yShift );
384 attemptSetSceneRect( QRectF( pos().x() + xShift, pos().y() + yShift, newSize.width(), newSize.height() ) );
391 const QStringList lines =
currentText().split(
'\n' );
395 const double penWidth =
frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
397 const double width = textWidth + 2 * mMarginX + 2 * penWidth;
398 const double height = fontHeight + 2 * mMarginY + 2 * penWidth;
400 return mLayout->convertToLayoutUnits(
QgsLayoutSize( width, height, Qgis::LayoutUnit::Millimeters ) );
405 return mFormat.
font();
410 layoutLabelElem.setAttribute( QStringLiteral(
"htmlState" ),
static_cast< int >( mMode ) );
412 layoutLabelElem.setAttribute( QStringLiteral(
"labelText" ), mText );
413 layoutLabelElem.setAttribute( QStringLiteral(
"marginX" ), QString::number( mMarginX ) );
414 layoutLabelElem.setAttribute( QStringLiteral(
"marginY" ), QString::number( mMarginY ) );
415 layoutLabelElem.setAttribute( QStringLiteral(
"halign" ), mHAlignment );
416 layoutLabelElem.setAttribute( QStringLiteral(
"valign" ), mVAlignment );
418 QDomElement textElem = mFormat.
writeXml( doc, rwContext );
419 layoutLabelElem.appendChild( textElem );
429 mText = itemElem.attribute( QStringLiteral(
"labelText" ) );
432 mMode =
static_cast< Mode >( itemElem.attribute( QStringLiteral(
"htmlState" ) ).toInt() );
435 bool marginXOk =
false;
436 bool marginYOk =
false;
437 mMarginX = itemElem.attribute( QStringLiteral(
"marginX" ) ).toDouble( &marginXOk );
438 mMarginY = itemElem.attribute( QStringLiteral(
"marginY" ) ).toDouble( &marginYOk );
439 if ( !marginXOk || !marginYOk )
442 const double margin = itemElem.attribute( QStringLiteral(
"margin" ), QStringLiteral(
"1.0" ) ).toDouble();
448 mHAlignment =
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( QStringLiteral(
"halign" ) ).toInt() );
451 mVAlignment =
static_cast< Qt::AlignmentFlag
>( itemElem.attribute( QStringLiteral(
"valign" ) ).toInt() );
454 QDomNodeList textFormatNodeList = itemElem.elementsByTagName( QStringLiteral(
"text-style" ) );
455 if ( !textFormatNodeList.isEmpty() )
457 QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
458 mFormat.
readXml( textFormatElem, context );
465 f.fromString( itemElem.attribute( QStringLiteral(
"font" ), QString() ) );
468 if ( f.pointSizeF() > 0 )
470 mFormat.
setSize( f.pointSizeF() );
473 else if ( f.pixelSize() > 0 )
475 mFormat.
setSize( f.pixelSize() );
480 const QDomNodeList fontColorList = itemElem.elementsByTagName( QStringLiteral(
"FontColor" ) );
481 if ( !fontColorList.isEmpty() )
483 const QDomElement fontColorElem = fontColorList.at( 0 ).toElement();
484 const int red = fontColorElem.attribute( QStringLiteral(
"red" ), QStringLiteral(
"0" ) ).toInt();
485 const int green = fontColorElem.attribute( QStringLiteral(
"green" ), QStringLiteral(
"0" ) ).toInt();
486 const int blue = fontColorElem.attribute( QStringLiteral(
"blue" ), QStringLiteral(
"0" ) ).toInt();
487 const int alpha = fontColorElem.attribute( QStringLiteral(
"alpha" ), QStringLiteral(
"255" ) ).toInt();
488 mFormat.
setColor( QColor( red, green, blue, alpha ) );
490 else if ( textFormatNodeList.isEmpty() )
492 mFormat.
setColor( QColor( 0, 0, 0 ) );
501 if ( !
id().isEmpty() )
509 return tr(
"<HTML Label>" );
515 const QString
text = mText;
516 if (
text.isEmpty() )
518 return tr(
"<Label>" );
520 if (
text.length() > 25 )
522 return QString( tr(
"%1…" ) ).arg(
text.left( 25 ).simplified() );
526 return text.simplified();
535 QRectF rectangle = rect();
536 const double penWidth =
frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
537 rectangle.adjust( -penWidth, -penWidth, penWidth, penWidth );
541 rectangle.adjust( mMarginX, 0, -mMarginX, 0 );
545 rectangle.adjust( 0, mMarginY, 0, -mMarginY );
554 prepareGeometryChange();
560 prepareGeometryChange();
567 refreshExpressionContext();
573 if ( evaluated == mText )
579void QgsLayoutItemLabel::itemShiftAdjustSize(
double newWidth,
double newHeight,
double &xShift,
double &yShift )
const
582 const double currentWidth = rect().width();
583 const double currentHeight = rect().height();
587 const double r = rotation();
588 if ( r >= 0 && r < 90 )
590 if ( mHAlignment == Qt::AlignHCenter )
592 xShift = - ( newWidth - currentWidth ) / 2.0;
594 else if ( mHAlignment == Qt::AlignRight )
596 xShift = - ( newWidth - currentWidth );
598 if ( mVAlignment == Qt::AlignVCenter )
600 yShift = -( newHeight - currentHeight ) / 2.0;
602 else if ( mVAlignment == Qt::AlignBottom )
604 yShift = - ( newHeight - currentHeight );
607 if ( r >= 90 && r < 180 )
609 if ( mHAlignment == Qt::AlignHCenter )
611 yShift = -( newHeight - currentHeight ) / 2.0;
613 else if ( mHAlignment == Qt::AlignRight )
615 yShift = -( newHeight - currentHeight );
617 if ( mVAlignment == Qt::AlignTop )
619 xShift = -( newWidth - currentWidth );
621 else if ( mVAlignment == Qt::AlignVCenter )
623 xShift = -( newWidth - currentWidth / 2.0 );
626 else if ( r >= 180 && r < 270 )
628 if ( mHAlignment == Qt::AlignHCenter )
630 xShift = -( newWidth - currentWidth ) / 2.0;
632 else if ( mHAlignment == Qt::AlignLeft )
634 xShift = -( newWidth - currentWidth );
636 if ( mVAlignment == Qt::AlignVCenter )
638 yShift = ( newHeight - currentHeight ) / 2.0;
640 else if ( mVAlignment == Qt::AlignTop )
642 yShift = ( newHeight - currentHeight );
645 else if ( r >= 270 && r < 360 )
647 if ( mHAlignment == Qt::AlignHCenter )
649 yShift = -( newHeight - currentHeight ) / 2.0;
651 else if ( mHAlignment == Qt::AlignLeft )
653 yShift = -( newHeight - currentHeight );
655 if ( mVAlignment == Qt::AlignBottom )
657 xShift = -( newWidth - currentWidth );
659 else if ( mVAlignment == Qt::AlignVCenter )
661 xShift = -( newWidth - currentWidth / 2.0 );
666QUrl QgsLayoutItemLabel::createStylesheetUrl()
const
669 stylesheet += QStringLiteral(
"body { margin: %1 %2;" ).arg( std::max( mMarginY * mHtmlUnitsToLayoutUnits, 0.0 ) ).arg( std::max( mMarginX * mHtmlUnitsToLayoutUnits, 0.0 ) );
670 QFont f = mFormat.
font();
673 case Qgis::RenderUnit::Millimeters:
674 f.setPointSizeF( mFormat.
size() / 0.352778 );
676 case Qgis::RenderUnit::Pixels:
677 f.setPixelSize( mFormat.
size() );
679 case Qgis::RenderUnit::Points:
680 f.setPointSizeF( mFormat.
size() );
682 case Qgis::RenderUnit::Inches:
683 f.setPointSizeF( mFormat.
size() * 72 );
685 case Qgis::RenderUnit::Unknown:
686 case Qgis::RenderUnit::Percentage:
687 case Qgis::RenderUnit::MetersInMapUnits:
688 case Qgis::RenderUnit::MapUnits:
693 stylesheet += QStringLiteral(
"color: rgba(%1,%2,%3,%4);" ).arg( mFormat.
color().red() ).arg( mFormat.
color().green() ).arg( mFormat.
color().blue() ).arg( QString::number( mFormat.
color().alphaF(),
'f', 4 ) );
694 stylesheet += QStringLiteral(
"text-align: %1; }" ).arg( mHAlignment == Qt::AlignLeft ? QStringLiteral(
"left" ) : mHAlignment == Qt::AlignRight ? QStringLiteral(
"right" ) : mHAlignment == Qt::AlignHCenter ? QStringLiteral(
"center" ) : QStringLiteral(
"justify" ) );
697 ba.append( stylesheet.toUtf8() );
698 QUrl cssFileURL = QUrl( QString(
"data:text/css;charset=utf-8;base64," + ba.toBase64() ) );
@ 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.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
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 QString asCSS(const QFont &font, double pointToPixelMultiplier=1.0)
Returns a CSS string representing the specified font as closely as possible.
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.
A layout item subclass for text labels.
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.
Layout graphical items for displaying a map.
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.
Base class for graphical items within a QgsLayout.
virtual void drawFrame(QgsRenderContext &context)
Draws the frame around the item.
virtual void setFrameStrokeWidth(QgsLayoutMeasurement width)
Sets the frame stroke width.
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.
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.
This class provides a method of storing measurements for use in QGIS layouts using a variety of diffe...
const QgsLayout * layout() const
Returns the layout the object is attached to.
void changed()
Emitted when the object's properties change.
QPointer< QgsLayout > mLayout
This class provides a method of storing sizes, consisting of a width and height, for use in QGIS layo...
static QgsRenderContext createRenderContextForLayout(QgsLayout *layout, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout and painter destination.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
QgsCoordinateReferenceSystem crs
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
The class is used as a container of context for various read/write operations on other 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.
This class is a composition of two QSettings instances:
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.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
void setSize(double size)
Sets the size for rendered text.
void setFont(const QFont &font)
Sets the font used for rendering text.
void setSizeUnit(Qgis::RenderUnit unit)
Sets the units for the size of rendered text.
void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Read settings from a DOM element.
Qgis::RenderUnit sizeUnit() const
Returns the units for the size of rendered text.
double size() const
Returns the size for rendered text.
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Write settings into a DOM element.
QColor color() const
Returns the color that text will be rendered in.
QFont font() const
Returns the font used for rendering text.
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 data sets.
QWebPage subclass which redirects JavaScript errors and console output to the QGIS message log.