QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
Loading...
Searching...
No Matches
qgslayoutitemlabel.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgslayoutitemlabel.cpp
3 -------------------
4 begin : October 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
18#include "qgslayoutitemlabel.h"
19
20#include <memory>
21
22#include "qgsdistancearea.h"
23#include "qgsexpression.h"
25#include "qgsfontutils.h"
26#include "qgslayout.h"
27#include "qgslayoutitemmap.h"
29#include "qgslayoutmodel.h"
32#include "qgslayoututils.h"
33#include "qgssettings.h"
34#include "qgstextformat.h"
35#include "qgstextrenderer.h"
36#include "qgsvectorlayer.h"
37
38#include <QCoreApplication>
39#include <QDate>
40#include <QDomElement>
41#include <QPainter>
42#include <QString>
43#include <QTextDocument>
44
45#include "moc_qgslayoutitemlabel.cpp"
46
47using namespace Qt::StringLiterals;
48
51{
52 mDistanceArea = std::make_unique<QgsDistanceArea>();
53 mHtmlUnitsToLayoutUnits = htmlUnitsToLayoutUnits();
54
55 //get default layout font from settings
56 const QgsSettings settings;
57 const QString defaultFontString = settings.value( u"LayoutDesigner/defaultFont"_s, QVariant(), QgsSettings::Gui ).toString();
58 if ( !defaultFontString.isEmpty() )
59 {
60 QFont f = mFormat.font();
61 QgsFontUtils::setFontFamily( f, defaultFontString );
62 mFormat.setFont( f );
63 }
64
65 //default to a 10 point font size
66 mFormat.setSize( 10 );
67 mFormat.setSizeUnit( Qgis::RenderUnit::Points );
68
69 connect( this, &QgsLayoutItem::sizePositionChanged, this, [this] { updateBoundingRect(); } );
70
71 //default to no background
72 setBackgroundEnabled( false );
73
74 //a label added while atlas preview is enabled needs to have the expression context set,
75 //otherwise fields in the label aren't correctly evaluated until atlas preview feature changes (#9457)
76 refreshExpressionContext();
77}
78
83
88
90{
91 return QgsApplication::getThemeIcon( u"/mLayoutItemLabel.svg"_s );
92}
93
95{
96 QPainter *painter = context.renderContext().painter();
97 const QgsScopedQPainterState painterState( painter );
98
99 const double penWidth = frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
100 const double xPenAdjust = mMarginX < 0 ? -penWidth : penWidth;
101 const double yPenAdjust = mMarginY < 0 ? -penWidth : penWidth;
102
103 QRectF painterRect;
104 if ( mMode == QgsLayoutItemLabel::ModeFont )
105 {
106 const double rectScale = context.renderContext().scaleFactor();
107 painterRect
108 = QRectF( ( xPenAdjust + mMarginX ) * rectScale, ( yPenAdjust + mMarginY ) * rectScale, ( rect().width() - 2 * xPenAdjust - 2 * mMarginX ) * rectScale, ( rect().height() - 2 * yPenAdjust - 2 * mMarginY ) * rectScale );
109 }
110 else
111 {
112 // The adjustment value was found through trial and error, the author has however no clue as to where it comes from
113#if QT_VERSION >= QT_VERSION_CHECK( 6, 7, 0 )
114 constexpr double adjustmentFactor = 4.18;
115#else
116 constexpr double adjustmentFactor = 3.77;
117#endif
118 const double rectScale = context.renderContext().scaleFactor() * adjustmentFactor;
119 // The left/right margin is handled by the stylesheet while the top/bottom margin is ignored by QTextDocument
120 painterRect = QRectF( 0, 0, ( rect().width() ) * rectScale, ( rect().height() - yPenAdjust - mMarginY ) * rectScale );
121 painter->translate( 0, ( yPenAdjust + mMarginY ) * context.renderContext().scaleFactor() );
122 painter->scale( context.renderContext().scaleFactor() / adjustmentFactor, context.renderContext().scaleFactor() / adjustmentFactor );
123 }
124
125 switch ( mMode )
126 {
127 case ModeHtml:
128 {
129 QTextDocument document;
130 document.setDocumentMargin( 0 );
131 document.setPageSize( QSizeF( painterRect.width() / context.renderContext().scaleFactor(), painterRect.height() / context.renderContext().scaleFactor() ) );
132 document.setDefaultStyleSheet( createStylesheet() );
133
134 document.setDefaultFont( createDefaultFont() );
135
136 QTextOption textOption = document.defaultTextOption();
137 textOption.setAlignment( mHAlignment );
138 document.setDefaultTextOption( textOption );
139
140 document.setHtml( u"<body>%1</body>"_s.arg( currentText() ) );
141 document.drawContents( painter, painterRect );
142 break;
143 }
144
145 case ModeFont:
146 {
149 drawText( painterRect, 0, QgsTextRenderer::convertQtHAlignment( mHAlignment ), currentText().split( '\n' ), context.renderContext(), mFormat, true, QgsTextRenderer::convertQtVAlignment( mVAlignment ), Qgis::TextRendererFlag::WrapLines );
150 break;
151 }
152 }
153}
154
155void QgsLayoutItemLabel::contentChanged()
156{
157 switch ( mMode )
158 {
159 case ModeHtml:
160 {
162 break;
163 }
164 case ModeFont:
166 break;
167 }
168}
169
170void QgsLayoutItemLabel::setText( const QString &text )
171{
172 mText = text;
173 emit changed();
174
175 contentChanged();
176
177 if ( mLayout && id().isEmpty() && mMode != ModeHtml )
178 {
179 //notify the model that the display name has changed
180 mLayout->itemsModel()->updateItemDisplayName( this );
181 }
182}
183
185{
186 if ( mode == mMode )
187 {
188 return;
189 }
190
191 mMode = mode;
192 contentChanged();
193
194 if ( mLayout && id().isEmpty() )
195 {
196 //notify the model that the display name has changed
197 mLayout->itemsModel()->updateItemDisplayName( this );
198 }
199}
200
201void QgsLayoutItemLabel::refreshExpressionContext()
202{
203 if ( !mLayout )
204 return;
205
206 QgsVectorLayer *layer = mLayout->reportContext().layer();
207 //setup distance area conversion
208 if ( layer )
209 {
210 mDistanceArea->setSourceCrs( layer->crs(), mLayout->project()->transformContext() );
211 }
212 else
213 {
214 //set to composition's reference map's crs
215 QgsLayoutItemMap *referenceMap = mLayout->referenceMap();
216 if ( referenceMap )
217 mDistanceArea->setSourceCrs( referenceMap->crs(), mLayout->project()->transformContext() );
218 }
219 mDistanceArea->setEllipsoid( mLayout->project()->ellipsoid() );
220 contentChanged();
221
222 update();
223}
224
225void QgsLayoutItemLabel::updateBoundingRect()
226{
227 QRectF rectangle = rect();
228 const double frameExtension = frameEnabled() ? pen().widthF() / 2.0 : 0.0;
229 if ( frameExtension > 0 )
230 rectangle.adjust( -frameExtension, -frameExtension, frameExtension, frameExtension );
231
232 if ( mMarginX < 0 )
233 {
234 rectangle.adjust( mMarginX, 0, -mMarginX, 0 );
235 }
236 if ( mMarginY < 0 )
237 {
238 rectangle.adjust( 0, mMarginY, 0, -mMarginY );
239 }
240
241 if ( rectangle != mCurrentRectangle )
242 {
243 prepareGeometryChange();
244 mCurrentRectangle = rectangle;
245 }
247}
248
250{
251 QString displayText = mText;
252 replaceDateText( displayText );
253
255
256 return QgsExpression::replaceExpressionText( displayText, &context, mDistanceArea.get() );
257}
258
259void QgsLayoutItemLabel::replaceDateText( QString &text ) const
260{
261 const QString constant = u"$CURRENT_DATE"_s;
262 const int currentDatePos = text.indexOf( constant );
263 if ( currentDatePos != -1 )
264 {
265 //check if there is a bracket just after $CURRENT_DATE
266 QString formatText;
267 const int openingBracketPos = text.indexOf( '(', currentDatePos );
268 const int closingBracketPos = text.indexOf( ')', openingBracketPos + 1 );
269 if ( openingBracketPos != -1 && closingBracketPos != -1 && ( closingBracketPos - openingBracketPos ) > 1 && openingBracketPos == currentDatePos + constant.size() )
270 {
271 formatText = text.mid( openingBracketPos + 1, closingBracketPos - openingBracketPos - 1 );
272 text.replace( currentDatePos, closingBracketPos - currentDatePos + 1, QDate::currentDate().toString( formatText ) );
273 }
274 else //no bracket
275 {
276 text.replace( "$CURRENT_DATE"_L1, QDate::currentDate().toString() );
277 }
278 }
279}
280
281void QgsLayoutItemLabel::setFont( const QFont &f )
282{
283 mFormat.setFont( f );
284 if ( f.pointSizeF() > 0 )
285 mFormat.setSize( f.pointSizeF() );
287}
288
290{
291 return mFormat;
292}
293
295{
296 mFormat = format;
298}
299
300void QgsLayoutItemLabel::setMargin( const double m )
301{
302 mMarginX = m;
303 mMarginY = m;
304 updateBoundingRect();
305}
306
307void QgsLayoutItemLabel::setMarginX( const double margin )
308{
309 mMarginX = margin;
310 updateBoundingRect();
311}
312
313void QgsLayoutItemLabel::setMarginY( const double margin )
314{
315 mMarginY = margin;
316 updateBoundingRect();
317}
318
320{
321 const QSizeF newSize = sizeForText();
322
323 //keep alignment point constant
324 double xShift = 0;
325 double yShift = 0;
326
327 itemShiftAdjustSize( newSize.width(), newSize.height(), xShift, yShift );
328
329 //update rect for data defined size and position
330 attemptSetSceneRect( QRectF( pos().x() + xShift, pos().y() + yShift, newSize.width(), newSize.height() ) );
331}
332
334{
335 const QSizeF newSize = sizeForText();
336 const double newWidth = newSize.width();
337 const double newHeight = newSize.height();
338 const double currentWidth = rect().width();
339 const double currentHeight = rect().height();
340
341 //keep reference point constant
342 double xShift = 0;
343 double yShift = 0;
344 switch ( referencePoint )
345 {
347 xShift = 0;
348 yShift = 0;
349 break;
351 xShift = -( newWidth - currentWidth ) / 2.0;
352 yShift = 0;
353 break;
354
356 xShift = -( newWidth - currentWidth );
357 yShift = 0;
358 break;
359
361 xShift = 0;
362 yShift = -( newHeight - currentHeight ) / 2.0;
363 break;
364
366 xShift = -( newWidth - currentWidth ) / 2.0;
367 yShift = -( newHeight - currentHeight ) / 2.0;
368 break;
369
371 xShift = -( newWidth - currentWidth );
372 yShift = -( newHeight - currentHeight ) / 2.0;
373 break;
374
376 xShift = 0;
377 yShift = -( newHeight - currentHeight );
378 break;
379
381 xShift = -( newWidth - currentWidth ) / 2.0;
382 yShift = -( newHeight - currentHeight );
383 break;
384
386 xShift = -( newWidth - currentWidth );
387 yShift = -( newHeight - currentHeight );
388 break;
389 }
390
391 //update rect for data defined size and position
392 attemptSetSceneRect( QRectF( pos().x() + xShift, pos().y() + yShift, newSize.width(), newSize.height() ) );
393}
394
396{
399
400 const QStringList lines = currentText().split( '\n' );
401 const double textWidth = std::ceil( QgsTextRenderer::textWidth( context, mFormat, lines ) + 1 ) / context.convertToPainterUnits( 1, Qgis::RenderUnit::Millimeters );
402 const double fontHeight = std::ceil( QgsTextRenderer::textHeight( context, mFormat, lines ) + 1 ) / context.convertToPainterUnits( 1, Qgis::RenderUnit::Millimeters );
403
404 const double penWidth = frameEnabled() ? ( pen().widthF() / 2.0 ) : 0;
405
406 const double width = textWidth + 2 * mMarginX + 2 * penWidth;
407 const double height = fontHeight + 2 * mMarginY + 2 * penWidth;
408
409 return mLayout->convertToLayoutUnits( QgsLayoutSize( width, height, Qgis::LayoutUnit::Millimeters ) );
410}
411
413{
414 return mFormat.font();
415}
416
417bool QgsLayoutItemLabel::writePropertiesToElement( QDomElement &layoutLabelElem, QDomDocument &doc, const QgsReadWriteContext &rwContext ) const
418{
419 layoutLabelElem.setAttribute( u"htmlState"_s, static_cast< int >( mMode ) );
420
421 layoutLabelElem.setAttribute( u"labelText"_s, mText );
422 layoutLabelElem.setAttribute( u"marginX"_s, QString::number( mMarginX ) );
423 layoutLabelElem.setAttribute( u"marginY"_s, QString::number( mMarginY ) );
424 layoutLabelElem.setAttribute( u"halign"_s, mHAlignment );
425 layoutLabelElem.setAttribute( u"valign"_s, mVAlignment );
426
427 QDomElement textElem = mFormat.writeXml( doc, rwContext );
428 layoutLabelElem.appendChild( textElem );
429
430 return true;
431}
432
433bool QgsLayoutItemLabel::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &, const QgsReadWriteContext &context )
434{
435 //restore label specific properties
436
437 //text
438 mText = itemElem.attribute( u"labelText"_s );
439
440 //html state
441 mMode = static_cast< Mode >( itemElem.attribute( u"htmlState"_s ).toInt() );
442
443 //margin
444 bool marginXOk = false;
445 bool marginYOk = false;
446 mMarginX = itemElem.attribute( u"marginX"_s ).toDouble( &marginXOk );
447 mMarginY = itemElem.attribute( u"marginY"_s ).toDouble( &marginYOk );
448 if ( !marginXOk || !marginYOk )
449 {
450 //upgrade old projects where margins where stored in a single attribute
451 const double margin = itemElem.attribute( u"margin"_s, u"1.0"_s ).toDouble();
452 mMarginX = margin;
453 mMarginY = margin;
454 }
455
456 //Horizontal alignment
457 mHAlignment = static_cast< Qt::AlignmentFlag >( itemElem.attribute( u"halign"_s ).toInt() );
458
459 //Vertical alignment
460 mVAlignment = static_cast< Qt::AlignmentFlag >( itemElem.attribute( u"valign"_s ).toInt() );
461
462 //font
463 QDomNodeList textFormatNodeList = itemElem.elementsByTagName( u"text-style"_s );
464 if ( !textFormatNodeList.isEmpty() )
465 {
466 QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
467 mFormat.readXml( textFormatElem, context );
468 }
469 else
470 {
471 QFont f;
472 if ( !QgsFontUtils::setFromXmlChildNode( f, itemElem, u"LabelFont"_s ) )
473 {
474 f.fromString( itemElem.attribute( u"font"_s, QString() ) );
475 }
476 mFormat.setFont( f );
477 if ( f.pointSizeF() > 0 )
478 {
479 mFormat.setSize( f.pointSizeF() );
480 mFormat.setSizeUnit( Qgis::RenderUnit::Points );
481 }
482 else if ( f.pixelSize() > 0 )
483 {
484 mFormat.setSize( f.pixelSize() );
485 mFormat.setSizeUnit( Qgis::RenderUnit::Pixels );
486 }
487
488 //font color
489 const QDomNodeList fontColorList = itemElem.elementsByTagName( u"FontColor"_s );
490 if ( !fontColorList.isEmpty() )
491 {
492 const QDomElement fontColorElem = fontColorList.at( 0 ).toElement();
493 const int red = fontColorElem.attribute( u"red"_s, u"0"_s ).toInt();
494 const int green = fontColorElem.attribute( u"green"_s, u"0"_s ).toInt();
495 const int blue = fontColorElem.attribute( u"blue"_s, u"0"_s ).toInt();
496 const int alpha = fontColorElem.attribute( u"alpha"_s, u"255"_s ).toInt();
497 mFormat.setColor( QColor( red, green, blue, alpha ) );
498 }
499 else if ( textFormatNodeList.isEmpty() )
500 {
501 mFormat.setColor( QColor( 0, 0, 0 ) );
502 }
503 }
504
505 updateBoundingRect();
506
507 return true;
508}
509
511{
512 if ( !id().isEmpty() )
513 {
514 return id();
515 }
516
517 switch ( mMode )
518 {
519 case ModeHtml:
520 return tr( "<HTML Label>" );
521
522 case ModeFont:
523 {
524 //if no id, default to portion of label text
525 const QString text = mText;
526 if ( text.isEmpty() )
527 {
528 return tr( "<Label>" );
529 }
530 if ( text.length() > 25 )
531 {
532 return QString( tr( "%1…" ) ).arg( text.left( 25 ).simplified() );
533 }
534 else
535 {
536 return text.simplified();
537 }
538 }
539 }
540 return QString(); // no warnings
541}
542
544{
545 return mCurrentRectangle;
546}
547
549{
551 updateBoundingRect();
552}
553
555{
557 updateBoundingRect();
558}
559
561{
564 refreshExpressionContext();
565}
566
568{
569 const QString evaluated = currentText();
570 if ( evaluated == mText )
571 return; // no changes
572
573 setText( evaluated );
574}
575
576void QgsLayoutItemLabel::itemShiftAdjustSize( double newWidth, double newHeight, double &xShift, double &yShift ) const
577{
578 //keep alignment point constant
579 const double currentWidth = rect().width();
580 const double currentHeight = rect().height();
581 xShift = 0;
582 yShift = 0;
583
584 const double r = rotation();
585 if ( r >= 0 && r < 90 )
586 {
587 if ( mHAlignment == Qt::AlignHCenter )
588 {
589 xShift = -( newWidth - currentWidth ) / 2.0;
590 }
591 else if ( mHAlignment == Qt::AlignRight )
592 {
593 xShift = -( newWidth - currentWidth );
594 }
595 if ( mVAlignment == Qt::AlignVCenter )
596 {
597 yShift = -( newHeight - currentHeight ) / 2.0;
598 }
599 else if ( mVAlignment == Qt::AlignBottom )
600 {
601 yShift = -( newHeight - currentHeight );
602 }
603 }
604 if ( r >= 90 && r < 180 )
605 {
606 if ( mHAlignment == Qt::AlignHCenter )
607 {
608 yShift = -( newHeight - currentHeight ) / 2.0;
609 }
610 else if ( mHAlignment == Qt::AlignRight )
611 {
612 yShift = -( newHeight - currentHeight );
613 }
614 if ( mVAlignment == Qt::AlignTop )
615 {
616 xShift = -( newWidth - currentWidth );
617 }
618 else if ( mVAlignment == Qt::AlignVCenter )
619 {
620 xShift = -( newWidth - currentWidth / 2.0 );
621 }
622 }
623 else if ( r >= 180 && r < 270 )
624 {
625 if ( mHAlignment == Qt::AlignHCenter )
626 {
627 xShift = -( newWidth - currentWidth ) / 2.0;
628 }
629 else if ( mHAlignment == Qt::AlignLeft )
630 {
631 xShift = -( newWidth - currentWidth );
632 }
633 if ( mVAlignment == Qt::AlignVCenter )
634 {
635 yShift = ( newHeight - currentHeight ) / 2.0;
636 }
637 else if ( mVAlignment == Qt::AlignTop )
638 {
639 yShift = ( newHeight - currentHeight );
640 }
641 }
642 else if ( r >= 270 && r < 360 )
643 {
644 if ( mHAlignment == Qt::AlignHCenter )
645 {
646 yShift = -( newHeight - currentHeight ) / 2.0;
647 }
648 else if ( mHAlignment == Qt::AlignLeft )
649 {
650 yShift = -( newHeight - currentHeight );
651 }
652 if ( mVAlignment == Qt::AlignBottom )
653 {
654 xShift = -( newWidth - currentWidth );
655 }
656 else if ( mVAlignment == Qt::AlignVCenter )
657 {
658 xShift = -( newWidth - currentWidth / 2.0 );
659 }
660 }
661}
662
663QFont QgsLayoutItemLabel::createDefaultFont() const
664{
665 QFont f = mFormat.font();
666 switch ( mFormat.sizeUnit() )
667 {
669 f.setPointSizeF( mFormat.size() / 0.352778 );
670 break;
672 f.setPixelSize( mFormat.size() );
673 break;
675 f.setPointSizeF( mFormat.size() );
676 break;
678 f.setPointSizeF( mFormat.size() * 72 );
679 break;
684 break;
685 }
686 return f;
687}
688
689double QgsLayoutItemLabel::htmlUnitsToLayoutUnits()
690{
691 if ( !mLayout )
692 {
693 return 1.0;
694 }
695
696 //TODO : fix this more precisely so that the label's default text size is the same with or without "display as html"
697 return mLayout->convertToLayoutUnits( QgsLayoutMeasurement( mLayout->renderContext().dpi() / 72.0, Qgis::LayoutUnit::Millimeters ) ); //webkit seems to assume a standard dpi of 72
698}
699
700QString QgsLayoutItemLabel::createStylesheet() const
701{
702 QString stylesheet;
703
704 stylesheet += u"body { margin: %1 %2;"_s.arg( std::max( mMarginY * mHtmlUnitsToLayoutUnits, 0.0 ) ).arg( std::max( mMarginX * mHtmlUnitsToLayoutUnits, 0.0 ) );
705 stylesheet += mFormat.asCSS( 0.352778 * mHtmlUnitsToLayoutUnits );
706 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 );
707
708 return stylesheet;
709}
710
711QUrl QgsLayoutItemLabel::createStylesheetUrl() const
712{
713 QByteArray ba;
714 ba.append( createStylesheet().toUtf8() );
715 QUrl cssFileURL = QUrl( QString( "data:text/css;charset=utf-8;base64," + ba.toBase64() ) );
716
717 return cssFileURL;
718}
@ Millimeters
Millimeters.
Definition qgis.h:5361
@ Percentage
Percentage of another measurement (e.g., canvas size, feature size).
Definition qgis.h:5344
@ Millimeters
Millimeters.
Definition qgis.h:5341
@ Points
Points (e.g., for font sizes).
Definition qgis.h:5345
@ Unknown
Mixed or unknown units.
Definition qgis.h:5347
@ MapUnits
Map units.
Definition qgis.h:5342
@ Pixels
Pixels.
Definition qgis.h:5343
@ Inches
Inches.
Definition qgis.h:5346
@ MetersInMapUnits
Meters value as Map units.
Definition qgis.h:5348
@ ApplyScalingWorkaroundForTextRendering
Whether a scaling workaround designed to stablise the rendering of small font sizes (or for painters ...
Definition qgis.h:2859
@ WrapLines
Automatically wrap long lines of text.
Definition qgis.h:3522
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.
friend class QgsLayout
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.
@ Middle
Center 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
Definition qgsmaplayer.h:90
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.
Definition qgssettings.h:68
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.