36#include <QStyleOptionGraphicsItem>
39#define CACHE_SIZE_LIMIT 5000
42 : mRenderContext( context )
43 , mViewScaleFactor( viewScaleFactor )
51 , QGraphicsRectItem( nullptr )
52 , mUuid( QUuid::createUuid().toString() )
57 setFlags( flags() | QGraphicsItem::ItemUsesExtendedStyleOption | QGraphicsItem::ItemIsSelectable );
59 setCacheMode( QGraphicsItem::DeviceCoordinateCache );
63 mItemPosition =
QgsLayoutPoint( scenePos().x(), scenePos().y(), initialUnits );
64 mItemSize =
QgsLayoutSize( rect().width(), rect().height(), initialUnits );
70 initConnectionsToLayout();
75 mLayoutManagesZValue =
true;
76 mLayout->itemsModel()->addItemAtTop(
this );
80 mLayoutManagesZValue =
false;
90 mEffect->setEnabled( flags & QgsLayoutRenderContext::FlagUseAdvancedEffects );
93 setGraphicsEffect( mEffect.get() );
103 if (
mLayout && mLayoutManagesZValue )
105 mLayout->itemsModel()->removeItem(
this );
112 if ( !
id().isEmpty() )
120 return tr(
"<%1>" ).arg( metadata->visibleName() );
123 return tr(
"<item>" );
138 return QgsLayoutItem::Flags();
148 if ( !shouldBlockUndoCommands() )
149 mLayout->undoStack()->beginCommand(
this, tr(
"Change Item ID" ) );
153 if ( !shouldBlockUndoCommands() )
154 mLayout->undoStack()->endCommand();
161 mLayout->itemsModel()->updateItemDisplayName(
this );
169 QGraphicsRectItem::setSelected( selected );
173 mLayout->itemsModel()->updateItemSelectStatus(
this );
179 if ( visible == isVisible() )
185 std::unique_ptr< QgsAbstractLayoutUndoCommand > command;
186 if ( !shouldBlockUndoCommands() )
188 command.reset(
createCommand( visible ? tr(
"Show Item" ) : tr(
"Hide Item" ), 0 ) );
189 command->saveBeforeState();
192 QGraphicsItem::setVisible( visible );
196 command->saveAfterState();
197 mLayout->undoStack()->push( command.release() );
203 mLayout->itemsModel()->updateItemVisibility(
this );
209 if (
locked == mIsLocked )
214 if ( !shouldBlockUndoCommands() )
215 mLayout->undoStack()->beginCommand(
this,
locked ? tr(
"Lock Item" ) : tr(
"Unlock Item" ) );
219 if ( !shouldBlockUndoCommands() )
220 mLayout->undoStack()->endCommand();
225 mLayout->itemsModel()->updateItemLockStatus(
this );
234 return !mParentGroupUuid.isEmpty() &&
mLayout &&
static_cast< bool >(
mLayout->itemByUuid( mParentGroupUuid ) );
239 if ( !
mLayout || mParentGroupUuid.isEmpty() )
242 return qobject_cast< QgsLayoutItemGroup * >(
mLayout->itemByUuid( mParentGroupUuid ) );
248 mParentGroupUuid.clear();
250 mParentGroupUuid = group->
uuid();
251 setFlag( QGraphicsItem::ItemIsSelectable, !
static_cast< bool>( group ) );
277 if ( !
mLayout ||
mLayout->renderContext().currentExportLayer() == -1 )
283 return mLayout->renderContext().currentExportLayer() < layers;
301 if ( shouldDrawDebugRect() )
307 const bool previewRender = !
mLayout ||
mLayout->renderContext().isPreviewRender();
309 const bool useImageCache =
false;
312 if ( useImageCache || forceRasterOutput )
314 double widthInPixels = 0;
315 double heightInPixels = 0;
324 const double layoutUnitsToPixels =
mLayout ?
mLayout->convertFromLayoutUnits( 1, Qgis::LayoutUnit::Pixels ).length() : destinationDpi / 25.4;
325 widthInPixels = boundingRect().width() * layoutUnitsToPixels;
326 heightInPixels = boundingRect().height() * layoutUnitsToPixels;
333 if ( widthInPixels > heightInPixels )
337 heightInPixels /= scale;
343 widthInPixels /= scale;
345 destinationDpi = destinationDpi / scale;
348 if ( previewRender && !mItemCachedImage.isNull() &&
qgsDoubleNear( mItemCacheDpi, destinationDpi ) )
353 preparePainter( painter );
354 const double cacheScale = destinationDpi / mItemCacheDpi;
356 painter->drawImage( boundingRect().x() * context.
scaleFactor() / cacheScale,
357 boundingRect().y() * context.
scaleFactor() / cacheScale, mItemCachedImage );
362 QImage image = QImage( widthInPixels, heightInPixels, QImage::Format_ARGB32 );
363 image.fill( Qt::transparent );
364 image.setDotsPerMeterX( 1000 * destinationDpi * 25.4 );
365 image.setDotsPerMeterY( 1000 * destinationDpi * 25.4 );
366 QPainter p( &image );
368 preparePainter( &p );
380 draw( itemRenderContext );
391 painter->drawImage( boundingRect().x() * context.
scaleFactor(),
392 boundingRect().y() * context.
scaleFactor(), image );
396 mItemCacheDpi = destinationDpi;
397 mItemCachedImage = image;
405 preparePainter( painter );
415 draw( itemRenderContext );
429 if ( point == mReferencePoint )
434 mReferencePoint = point;
437 updateStoredItemPosition();
461 const QSizeF targetSizeLayoutUnits =
mLayout->convertToLayoutUnits( evaluatedSize );
462 QSizeF actualSizeLayoutUnits = applyMinimumSize( targetSizeLayoutUnits );
463 actualSizeLayoutUnits = applyFixedSize( actualSizeLayoutUnits );
466 if ( actualSizeLayoutUnits == rect().size() )
472 mItemSize = actualSizeTargetUnits;
474 setRect( 0, 0, actualSizeLayoutUnits.width(), actualSizeLayoutUnits.height() );
491 point =
mLayout->pageCollection()->pagePositionToAbsolute(
page, p );
498 point.
setX( point.
x() + bleed );
499 point.
setY( point.
y() + bleed );
503 if ( !useReferencePoint )
508 evaluatedPoint = applyDataDefinedPosition( evaluatedPoint );
509 const QPointF evaluatedPointLayoutUnits =
mLayout->convertToLayoutUnits( evaluatedPoint );
511 if ( topLeftPointLayoutUnits == scenePos() && point.
units() == mItemPosition.
units() )
518 mItemPosition = referencePointTargetUnits;
519 setScenePos( topLeftPointLayoutUnits );
525 const QPointF newPos = rect.topLeft();
527 blockSignals(
true );
535 blockSignals(
false );
543 moveBy( deltaX, deltaY );
549 itemPos.
setX( itemPos.
x() + deltaPos.
x() );
550 itemPos.
setY( itemPos.
y() + deltaPos.
y() );
559 return mLayout->pageCollection()->pageNumberForPoint( pos() );
574 p.ry() -= pageItem->pos().y();
584 return mLayout->convertFromLayoutUnits( p, mItemPosition.
units() );
587void QgsLayoutItem::setScenePos(
const QPointF destinationPos )
592 if (
auto *lParentItem = parentItem() )
593 setPos( pos() + ( destinationPos - scenePos() ) + lParentItem->scenePos() );
595 setPos( pos() + ( destinationPos - scenePos() ) );
598bool QgsLayoutItem::shouldBlockUndoCommands()
const
615 return !mEvaluatedExcludeFromExports;
620 return mItemRotation;
625 QDomElement element = doc.createElement( QStringLiteral(
"LayoutItem" ) );
626 element.setAttribute( QStringLiteral(
"type" ), QString::number(
type() ) );
628 element.setAttribute( QStringLiteral(
"uuid" ), mUuid );
629 element.setAttribute( QStringLiteral(
"templateUuid" ), mUuid );
630 element.setAttribute( QStringLiteral(
"id" ), mId );
631 element.setAttribute( QStringLiteral(
"referencePoint" ), QString::number(
static_cast< int >( mReferencePoint ) ) );
632 element.setAttribute( QStringLiteral(
"position" ), mItemPosition.
encodePoint() );
634 element.setAttribute( QStringLiteral(
"size" ), mItemSize.
encodeSize() );
635 element.setAttribute( QStringLiteral(
"itemRotation" ), QString::number( mItemRotation ) );
636 element.setAttribute( QStringLiteral(
"groupUuid" ), mParentGroupUuid );
638 element.setAttribute( QStringLiteral(
"zValue" ), QString::number( zValue() ) );
639 element.setAttribute( QStringLiteral(
"visibility" ), isVisible() );
643 element.setAttribute( QStringLiteral(
"positionLock" ), QStringLiteral(
"true" ) );
647 element.setAttribute( QStringLiteral(
"positionLock" ), QStringLiteral(
"false" ) );
653 element.setAttribute( QStringLiteral(
"frame" ), QStringLiteral(
"true" ) );
657 element.setAttribute( QStringLiteral(
"frame" ), QStringLiteral(
"false" ) );
663 element.setAttribute( QStringLiteral(
"background" ), QStringLiteral(
"true" ) );
667 element.setAttribute( QStringLiteral(
"background" ), QStringLiteral(
"false" ) );
671 QDomElement frameColorElem = doc.createElement( QStringLiteral(
"FrameColor" ) );
672 frameColorElem.setAttribute( QStringLiteral(
"red" ), QString::number( mFrameColor.red() ) );
673 frameColorElem.setAttribute( QStringLiteral(
"green" ), QString::number( mFrameColor.green() ) );
674 frameColorElem.setAttribute( QStringLiteral(
"blue" ), QString::number( mFrameColor.blue() ) );
675 frameColorElem.setAttribute( QStringLiteral(
"alpha" ), QString::number( mFrameColor.alpha() ) );
676 element.appendChild( frameColorElem );
677 element.setAttribute( QStringLiteral(
"outlineWidthM" ), mFrameWidth.
encodeMeasurement() );
681 QDomElement bgColorElem = doc.createElement( QStringLiteral(
"BackgroundColor" ) );
682 bgColorElem.setAttribute( QStringLiteral(
"red" ), QString::number( mBackgroundColor.red() ) );
683 bgColorElem.setAttribute( QStringLiteral(
"green" ), QString::number( mBackgroundColor.green() ) );
684 bgColorElem.setAttribute( QStringLiteral(
"blue" ), QString::number( mBackgroundColor.blue() ) );
685 bgColorElem.setAttribute( QStringLiteral(
"alpha" ), QString::number( mBackgroundColor.alpha() ) );
686 element.appendChild( bgColorElem );
692 element.setAttribute( QStringLiteral(
"opacity" ), QString::number( mOpacity ) );
694 element.setAttribute( QStringLiteral(
"excludeFromExports" ), mExcludeFromExports );
699 parentElement.appendChild( element );
706 if ( element.nodeName() != QLatin1String(
"LayoutItem" ) )
713 mBlockUndoCommands =
true;
714 mUuid = element.attribute( QStringLiteral(
"uuid" ), QUuid::createUuid().toString() );
715 setId( element.attribute( QStringLiteral(
"id" ) ) );
716 mReferencePoint =
static_cast< ReferencePoint >( element.attribute( QStringLiteral(
"referencePoint" ) ).toInt() );
717 setItemRotation( element.attribute( QStringLiteral(
"itemRotation" ), QStringLiteral(
"0" ) ).toDouble() );
721 mParentGroupUuid = element.attribute( QStringLiteral(
"groupUuid" ) );
722 if ( !mParentGroupUuid.isEmpty() )
726 group->addItem(
this );
729 mTemplateUuid = element.attribute( QStringLiteral(
"templateUuid" ) );
732 const QString positionLock = element.attribute( QStringLiteral(
"positionLock" ) );
733 if ( positionLock.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
742 setVisibility( element.attribute( QStringLiteral(
"visibility" ), QStringLiteral(
"1" ) ) != QLatin1String(
"0" ) );
743 setZValue( element.attribute( QStringLiteral(
"zValue" ) ).toDouble() );
746 const QString frame = element.attribute( QStringLiteral(
"frame" ) );
747 if ( frame.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
757 const QString background = element.attribute( QStringLiteral(
"background" ) );
758 if ( background.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
770 const QDomNodeList frameColorList = element.elementsByTagName( QStringLiteral(
"FrameColor" ) );
771 if ( !frameColorList.isEmpty() )
773 const QDomElement frameColorElem = frameColorList.at( 0 ).toElement();
775 bool greenOk =
false;
777 bool alphaOk =
false;
778 int penRed, penGreen, penBlue, penAlpha;
780 penRed = frameColorElem.attribute( QStringLiteral(
"red" ) ).toDouble( &redOk );
781 penGreen = frameColorElem.attribute( QStringLiteral(
"green" ) ).toDouble( &greenOk );
782 penBlue = frameColorElem.attribute( QStringLiteral(
"blue" ) ).toDouble( &blueOk );
783 penAlpha = frameColorElem.attribute( QStringLiteral(
"alpha" ) ).toDouble( &alphaOk );
785 if ( redOk && greenOk && blueOk && alphaOk )
787 mFrameColor = QColor( penRed, penGreen, penBlue, penAlpha );
793 const QDomNodeList bgColorList = element.elementsByTagName( QStringLiteral(
"BackgroundColor" ) );
794 if ( !bgColorList.isEmpty() )
796 const QDomElement bgColorElem = bgColorList.at( 0 ).toElement();
797 bool redOk, greenOk, blueOk, alphaOk;
798 int bgRed, bgGreen, bgBlue, bgAlpha;
799 bgRed = bgColorElem.attribute( QStringLiteral(
"red" ) ).toDouble( &redOk );
800 bgGreen = bgColorElem.attribute( QStringLiteral(
"green" ) ).toDouble( &greenOk );
801 bgBlue = bgColorElem.attribute( QStringLiteral(
"blue" ) ).toDouble( &blueOk );
802 bgAlpha = bgColorElem.attribute( QStringLiteral(
"alpha" ) ).toDouble( &alphaOk );
803 if ( redOk && greenOk && blueOk && alphaOk )
805 mBackgroundColor = QColor( bgRed, bgGreen, bgBlue, bgAlpha );
806 setBrush( QBrush( mBackgroundColor, Qt::SolidPattern ) );
816 if ( element.hasAttribute( QStringLiteral(
"opacity" ) ) )
818 setItemOpacity( element.attribute( QStringLiteral(
"opacity" ), QStringLiteral(
"1" ) ).toDouble() );
822 setItemOpacity( 1.0 - element.attribute( QStringLiteral(
"transparency" ), QStringLiteral(
"0" ) ).toInt() / 100.0 );
825 mExcludeFromExports = element.attribute( QStringLiteral(
"excludeFromExports" ), QStringLiteral(
"0" ) ).toInt();
826 mEvaluatedExcludeFromExports = mExcludeFromExports;
830 mBlockUndoCommands =
false;
843 return new QgsLayoutItemUndoCommand(
this, text,
id, parent );
861 if ( mFrameColor == color )
874 if ( mFrameWidth == width )
886 if ( mFrameJoinStyle == style )
891 mFrameJoinStyle = style;
893 QPen itemPen = pen();
894 itemPen.setJoinStyle( mFrameJoinStyle );
907 mBackgroundColor = color;
923 if ( !mItemCachedImage.isNull() )
929 return mExcludeFromExports;
934 mExcludeFromExports = exclude;
940 return itemFlags() & Flag::FlagOverridesPaint ? false : mEvaluatedOpacity < 1.0;
946 blendMode() != QPainter::CompositionMode_SourceOver;
956 return pen().widthF() / 2.0;
962 return rect().adjusted( -frameBleed, -frameBleed, frameBleed, frameBleed );
985 mLayout->undoStack()->beginCommand(
this, commandText, command );
991 mLayout->undoStack()->endCommand();
997 mLayout->undoStack()->cancelCommand();
1013void QgsLayoutItem::applyDataDefinedOrientation(
double &width,
double &height,
const QgsExpressionContext &context )
1017 if ( ok && !orientationString.isEmpty() )
1022 double heightD = 0.0, widthD = 0.0;
1023 switch ( orientation )
1027 heightD = std::max( height, width );
1028 widthD = std::min( height, width );
1033 heightD = std::min( height, width );
1034 widthD = std::max( height, width );
1063 double evaluatedWidth = size.
width();
1064 double evaluatedHeight = size.
height();
1068 evaluatedWidth = convertedSize.
width();
1069 evaluatedHeight = convertedSize.
height();
1077 applyDataDefinedOrientation( evaluatedWidth, evaluatedHeight, context );
1082double QgsLayoutItem::applyDataDefinedRotation(
const double rotation )
1091 return evaluatedRotation;
1131 const bool exclude = mExcludeFromExports;
1148 const double rotationRequired =
angle - rotation();
1151 mItemRotation =
angle;
1154void QgsLayoutItem::updateStoredItemPosition()
1157 mItemPosition =
mLayout->convertFromLayoutUnits( layoutPosReferencePoint, mItemPosition.
units() );
1162 double evaluatedAngle =
angle + rotation();
1164 mItemRotation = evaluatedAngle;
1166 QPointF itemTransformOrigin = mapFromScene( transformOrigin );
1185 Q_UNUSED( visitor );
1204 if ( !mItemCachedImage.isNull() )
1206 mItemCachedImage = QImage();
1225 painter->setRenderHint( QPainter::Antialiasing,
false );
1226 painter->setPen( Qt::NoPen );
1227 painter->setBrush( QColor( 100, 255, 100, 200 ) );
1228 painter->drawRect( rect() );
1234 path.addRect( QRectF( 0, 0, rect().width(), rect().height() ) );
1240 if ( !mFrame || !context.
painter() )
1243 QPainter *p = context.
painter();
1248 p->setBrush( Qt::NoBrush );
1256 if ( !mBackground || !context.
painter() )
1261 QPainter *p = context.
painter();
1262 p->setBrush( brush() );
1263 p->setPen( Qt::NoPen );
1272 bool fitsInCache =
false;
1273 const int xSize = QFontMetrics( QFont() ).horizontalAdvance(
'X' );
1274 const QImage refreshingImage =
QgsApplication::svgCache()->
svgAsImage( QStringLiteral(
":/images/composer/refreshing_item.svg" ), xSize * 3, QColor(), QColor(), 1, 1, fitsInCache );
1277 painter->scale( 1.0 / previewScaleFactor, 1.0 / previewScaleFactor );
1278 painter->drawImage( xSize, xSize, refreshingImage );
1289 mMinimumSize = size;
1308QPointF QgsLayoutItem::itemPositionAtReferencePoint(
const ReferencePoint reference,
const QSizeF size )
const
1310 switch ( reference )
1313 return QPointF( size.width() / 2.0, 0 );
1315 return QPointF( size.width(), 0 );
1317 return QPointF( 0, size.height() / 2.0 );
1319 return QPointF( size.width() / 2.0, size.height() / 2.0 );
1321 return QPointF( size.width(), size.height() / 2.0 );
1323 return QPointF( 0, size.height() );
1325 return QPointF( size.width() / 2.0, size.height() );
1327 return QPointF( size.width(), size.height() );
1329 return QPointF( 0, 0 );
1332 return QPointF( 0, 0 );
1337 const QPointF itemPosition = mapFromScene( position );
1338 const QPointF adjustedPointInsideItem = itemPosition - itemPositionAtReferencePoint( reference, size );
1339 return mapToScene( adjustedPointInsideItem );
1344 const QPointF pointWithinItem = itemPositionAtReferencePoint( reference, rect().size() );
1345 return mapToScene( pointWithinItem );
1350 const QPointF topLeft =
mLayout->convertToLayoutUnits( point );
1351 const QPointF refPoint = topLeft + itemPositionAtReferencePoint( mReferencePoint, rect().size() );
1352 return mLayout->convertFromLayoutUnits( refPoint, point.
units() );
1366void QgsLayoutItem::initConnectionsToLayout()
1373void QgsLayoutItem::preparePainter( QPainter *painter )
1375 if ( !painter || !painter->device() )
1380 painter->setRenderHint( QPainter::Antialiasing, shouldDrawAntialiased() );
1385bool QgsLayoutItem::shouldDrawAntialiased()
const
1394bool QgsLayoutItem::shouldDrawDebugRect()
const
1399QSizeF QgsLayoutItem::applyMinimumSize(
const QSizeF targetSize )
1405 const QSizeF minimumSizeLayoutUnits =
mLayout->convertToLayoutUnits(
minimumSize() );
1406 return targetSize.expandedTo( minimumSizeLayoutUnits );
1409QSizeF QgsLayoutItem::applyFixedSize(
const QSizeF targetSize )
1416 QSizeF size = targetSize;
1417 const QSizeF fixedSizeLayoutUnits =
mLayout->convertToLayoutUnits(
fixedSize() );
1418 if ( fixedSizeLayoutUnits.width() > 0 )
1419 size.setWidth( fixedSizeLayoutUnits.width() );
1420 if ( fixedSizeLayoutUnits.height() > 0 )
1421 size.setHeight( fixedSizeLayoutUnits.height() );
1428 double r = mItemRotation;
1440 if ( !transformPoint.isNull() )
1444 QLineF refLine = QLineF( mapToScene( transformPoint ), mapToScene( QPointF( 0, 0 ) ) );
1446 refLine.setAngle( refLine.angle() - r + rotation() );
1448 const QPointF rotatedReferencePoint = refLine.p2();
1449 setPos( rotatedReferencePoint );
1452 setTransformOriginPoint( 0, 0 );
1453 QGraphicsItem::setRotation( r );
1456 updateStoredItemPosition();
1471 mEvaluatedOpacity = opacity / 100.0;
1477 setOpacity( mEvaluatedOpacity );
1490 setPen( Qt::NoPen );
1500 itemPen = QPen( frameColor );
1504 itemPen = QPen( mFrameColor );
1506 itemPen.setJoinStyle( mFrameJoinStyle );
1509 itemPen.setWidthF(
mLayout->convertToLayoutUnits( mFrameWidth ) );
1511 itemPen.setWidthF( mFrameWidth.
length() );
1523 return useDataDefined ? brush().color() : mBackgroundColor;
1538 setBrush( QBrush( mBackgroundColor, Qt::SolidPattern ) );
1548 QPainter::CompositionMode
blendMode = mBlendMode;
1553 if ( ok && !blendStr.isEmpty() )
1555 const QString blendstr = blendStr.trimmed();
1561 mEffect->setCompositionMode(
blendMode );
LayoutUnit
Layout measurement units.
BlendMode
Blending modes defining the available composition modes that can be used when painting.
Base class for commands to undo/redo layout and layout object changes.
QColor valueAsColor(int key, const QgsExpressionContext &context, const QColor &defaultColor=QColor(), bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a color.
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.
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.
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.
static QgsPageSizeRegistry * pageSizeRegistry()
Returns the application's page size registry, used for managing layout page sizes.
static QgsLayoutItemRegistry * layoutItemRegistry()
Returns the application's layout item registry, used for layout item types.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QgsSvgCache * svgCache()
Returns the application's SVG cache, used for caching SVG images and handling parameter replacement w...
static QgsExpressionContextScope * layoutItemScope(const QgsLayoutItem *item)
Creates a new scope which contains variables and functions relating to a QgsLayoutItem.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
A geometry is the spatial representation of a feature.
static void multiplyOpacity(QImage &image, double factor, QgsFeedback *feedback=nullptr)
Multiplies opacity of image pixel values by a factor.
A QGraphicsEffect subclass used for rendering layout items onto a scene with custom composition modes...
A container for grouping several QgsLayoutItems.
Item representing the paper in a layout.
Orientation
Page orientation.
@ Landscape
Landscape orientation.
@ Portrait
Portrait orientation.
@ LayoutItem
Base class for items.
Contains settings and helpers relating to a render of a QgsLayoutItem.
QgsLayoutItemRenderContext(QgsRenderContext &context, double viewScaleFactor=1.0)
Constructor for QgsLayoutItemRenderContext.
virtual void drawDebugRect(QPainter *painter)
Draws a debugging rectangle of the item's current bounds within the specified painter.
virtual void drawFrame(QgsRenderContext &context)
Draws the frame around the item.
QgsAbstractLayoutUndoCommand * createCommand(const QString &text, int id, QUndoCommand *parent=nullptr) override
Creates a new layout undo command with the specified text and parent.
virtual QgsGeometry clipPath() const
Returns the clipping path generated by this item, in layout coordinates.
virtual QPainterPath framePath() const
Returns the path to use when drawing the item's frame or background.
virtual void cleanup()
Called just before a batch of items are deleted, allowing them to run cleanup tasks.
bool isGroupMember() const
Returns true if the item is part of a QgsLayoutItemGroup group.
QColor backgroundColor(bool useDataDefined=true) const
Returns the background color for this item.
void drawRefreshingOverlay(QPainter *painter, const QStyleOptionGraphicsItem *itemStyle)
Draws a "refreshing" overlay icon on the item.
bool writeXml(QDomElement &parentElement, QDomDocument &document, const QgsReadWriteContext &context) const
Stores the item state in a DOM element.
virtual void setFrameStrokeWidth(QgsLayoutMeasurement width)
Sets the frame stroke width.
virtual bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified style entity visitor, causing it to visit all style entities associated with th...
void refreshItemRotation(QPointF *origin=nullptr)
Refreshes an item's rotation by rechecking it against any possible overrides such as data defined rot...
UndoCommand
Layout item undo commands, used for collapsing undo commands.
QgsLayoutItemGroup * parentGroup() const
Returns the item's parent group, if the item is part of a QgsLayoutItemGroup group.
double itemRotation() const
Returns the current rotation for the item, in degrees clockwise.
QgsLayoutItem(QgsLayout *layout, bool manageZValue=true)
Constructor for QgsLayoutItem, with the specified parent layout.
virtual void setSelected(bool selected)
Sets whether the item should be selected.
QPointF adjustPointForReferencePosition(QPointF point, QSizeF size, ReferencePoint reference) const
Adjusts the specified point at which a reference position of the item sits and returns the top left c...
virtual void zoomContent(double factor, QPointF point)
Zooms content of item.
virtual void setItemRotation(double rotation, bool adjustPosition=true)
Sets the layout item's rotation, in degrees clockwise.
void rotationChanged(double newRotation)
Emitted on item rotation change.
virtual QgsLayoutItem::ExportLayerDetail exportLayerDetails() const
Returns the details for the specified current export layer.
void setBackgroundColor(const QColor &color)
Sets the background color for this item.
virtual QIcon icon() const
Returns the item's icon.
void paint(QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget) override
Handles preparing a paint surface for the layout item and painting the item's content.
bool excludeFromExports() const
Returns whether the item should be excluded from layout exports and prints.
virtual bool nextExportPart()
Moves to the next export part for a multi-layered export item, during a multi-layered export.
double itemOpacity() const
Returns the item's opacity.
virtual QRectF rectWithFrame() const
Returns the item's rectangular bounds, including any bleed caused by the item's frame.
void beginCommand(const QString &commandText, UndoCommand command=UndoNone)
Starts new undo command for this item.
void cancelCommand()
Cancels the current item command and discards it.
void setItemOpacity(double opacity)
Sets the item's opacity.
virtual void setVisibility(bool visible)
Sets whether the item is visible.
virtual void redraw()
Triggers a redraw (update) of the item.
QgsLayoutPoint positionWithUnits() const
Returns the item's current position, including units.
QgsLayoutPoint topLeftToReferencePoint(const QgsLayoutPoint &point) const
Returns the position for the reference point of the item, if the top-left of the item was placed at t...
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.
virtual void startLayeredExport()
Starts a multi-layer export operation.
virtual bool writePropertiesToElement(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Stores item state within an XML DOM element.
void endCommand()
Completes the current item command and push it onto the layout's undo stack.
void refreshItemSize()
Refreshes an item's size by rechecking it against any possible item fixed or minimum sizes.
int page() const
Returns the page the item is currently on, with the first page returning 0.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
virtual void setId(const QString &id)
Set the item's id name.
void setFrameStrokeColor(const QColor &color)
Sets the frame stroke color.
virtual void finalizeRestoreFromXml()
Called after all pending items have been restored from XML.
void setFrameJoinStyle(Qt::PenJoinStyle style)
Sets the join style used when drawing the item's frame.
void refreshBackgroundColor(bool updateItem=true)
Refresh item's background color, considering data defined colors.
virtual void rotateItem(double angle, QPointF transformOrigin)
Rotates the item by a specified angle in degrees clockwise around a specified reference point.
bool readXml(const QDomElement &itemElement, const QDomDocument &document, const QgsReadWriteContext &context)
Sets the item state from a DOM element.
virtual void setFrameEnabled(bool drawFrame)
Sets whether this item has a frame drawn around it or not.
void setLocked(bool locked)
Sets whether the item is locked, preventing mouse interactions with the item.
~QgsLayoutItem() override
int type() const override
Returns a unique graphics item type identifier.
virtual void drawBackground(QgsRenderContext &context)
Draws the background for the item.
virtual QString displayName() const
Gets item display name.
virtual QgsLayoutSize minimumSize() const
Returns the minimum allowed size of the item, if applicable, or an empty size if item can be freely r...
virtual void attemptResize(const QgsLayoutSize &size, bool includesFrame=false)
Attempts to resize the item to a specified target size.
virtual bool requiresRasterization() const
Returns true if the item is drawn in such a way that forces the whole layout to be rasterized when ex...
bool shouldDrawItem() const
Returns whether the item should be drawn in the current context.
virtual void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties)
Refreshes a data defined property for the item by reevaluating the property's value and redrawing the...
virtual void moveContent(double dx, double dy)
Moves the content of the item, by a specified dx and dy in layout units.
@ FlagOverridesPaint
Item overrides the default layout item painting method.
virtual void stopLayeredExport()
Stops a multi-layer export operation.
virtual bool containsAdvancedEffects() const
Returns true if the item contains contents with blend modes or transparency effects which can only be...
virtual QgsLayoutSize fixedSize() const
Returns the fixed size of the item, if applicable, or an empty size if item can be freely resized.
virtual void setMoveContentPreviewOffset(double dx, double dy)
Sets temporary offset for the item, by a specified dx and dy in layout units.
void setExcludeFromExports(bool exclude)
Sets whether the item should be excluded from layout exports and prints.
void sizePositionChanged()
Emitted when the item's size or position changes.
void lockChanged()
Emitted if the item's lock status changes.
virtual QSizeF applyItemSizeConstraint(QSizeF targetSize)
Applies any item-specific size constraint handling to a given targetSize in layout units.
virtual void invalidateCache()
Forces a deferred update of any cached image the item uses.
void refreshFrame(bool updateItem=true)
Refresh item's frame, considering data defined colors and frame size.
virtual QString uuid() const
Returns the item identification string.
virtual void attemptMove(const QgsLayoutPoint &point, bool useReferencePoint=true, bool includesFrame=false, int page=-1)
Attempts to move the item to a specified point.
QPointF pagePos() const
Returns the item's position (in layout units) relative to the top left corner of its current page.
QString id() const
Returns the item's ID name.
void setBlendMode(QPainter::CompositionMode mode)
Sets the item's composition blending mode.
bool frameEnabled() const
Returns true if the item includes a frame.
void frameChanged()
Emitted if the item's frame style changes.
virtual Flags itemFlags() const
Returns the item's flags, which indicate how the item behaves.
void attemptMoveBy(double deltaX, double deltaY)
Attempts to shift the item's position by a specified deltaX and deltaY, in layout units.
void setReferencePoint(ReferencePoint point)
Sets the reference point for positioning of the layout item.
virtual bool readPropertiesFromElement(const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context)
Sets item state from a DOM element.
ExportLayerBehavior
Behavior of item when exporting to layered outputs.
@ CanGroupWithAnyOtherItem
Item can be placed on a layer with any other item (default behavior)
virtual Q_DECL_DEPRECATED int numberExportLayers() const
Returns the number of layers that this item requires for exporting during layered exports (e....
virtual bool isRefreshing() const
Returns true if the item is currently refreshing content in the background.
void refreshBlendMode()
Refresh item's blend mode, considering data defined blend mode.
void setParentGroup(QgsLayoutItemGroup *group)
Sets the item's parent group.
QPointF positionAtReferencePoint(ReferencePoint reference) const
Returns the current position (in layout units) of a reference point for the item.
void refreshOpacity(bool updateItem=true)
Refresh item's opacity, considering data defined opacity.
QgsLayoutSize applyDataDefinedSize(const QgsLayoutSize &size)
Applies any present data defined size overrides to the specified layout size.
virtual void setMinimumSize(const QgsLayoutSize &size)
Sets the minimum allowed size for the layout item.
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.
virtual double estimatedFrameBleed() const
Returns the estimated amount the item's frame bleeds outside the item's actual rectangle.
virtual ExportLayerBehavior exportLayerBehavior() const
Returns the behavior of this item during exporting to layered exports (e.g.
void setBackgroundEnabled(bool drawBackground)
Sets whether this item has a background drawn under it or not.
void refreshItemPosition()
Refreshes an item's position by rechecking it against any possible overrides such as data defined pos...
virtual void setFixedSize(const QgsLayoutSize &size)
Sets a fixed size for the layout item, which prevents it from being freely resized.
QPainter::CompositionMode blendMode() const
Returns the item's composition blending mode.
virtual void draw(QgsLayoutItemRenderContext &context)=0
Draws the item's contents using the specified item render context.
QgsLayoutPoint pagePositionWithUnits() const
Returns the item's position (in item units) relative to the top left corner of its current page.
This class provides a method of storing measurements for use in QGIS layouts using a variety of diffe...
static QgsLayoutMeasurement decodeMeasurement(const QString &string)
Decodes a measurement from a string.
QString encodeMeasurement() const
Encodes the layout measurement to a string.
double length() const
Returns the length of the measurement.
A base class for objects which belong to a layout.
QgsPropertyCollection mDataDefinedProperties
bool readObjectPropertiesFromElement(const QDomElement &parentElement, const QDomDocument &document, const QgsReadWriteContext &context)
Sets object properties from a DOM element.
const QgsLayout * layout() const
Returns the layout the object is attached to.
void changed()
Emitted when the object's properties change.
virtual void refresh()
Refreshes the object, causing a recalculation of any property overrides.
QPointer< QgsLayout > mLayout
DataDefinedProperty
Data defined properties for different item types.
@ PaperOrientation
Paper orientation.
@ ItemWidth
Width of item.
@ ItemHeight
Height of item.
@ BlendMode
Item blend mode.
@ AllProperties
All properties for item.
@ PositionY
Y position on page.
@ ExcludeFromExports
Exclude item from exports.
@ BackgroundColor
Item background color.
@ ItemRotation
Rotation of item.
@ PresetPaperSize
Preset paper size for composition.
@ PositionX
X position on page.
@ FrameColor
Item frame color.
QgsExpressionContext createExpressionContext() const override
Creates an expression context relating to the objects' current state.
bool writeObjectPropertiesToElement(QDomElement &parentElement, QDomDocument &document, const QgsReadWriteContext &context) const
Stores object properties within an XML DOM element.
This class provides a method of storing points, consisting of an x and y coordinate,...
double x() const
Returns x coordinate of point.
QPointF toQPointF() const
Converts the layout point to a QPointF.
QString encodePoint() const
Encodes the layout point to a string.
void setX(const double x)
Sets the x coordinate of point.
static QgsLayoutPoint decodePoint(const QString &string)
Decodes a point from a string.
double y() const
Returns y coordinate of point.
Qgis::LayoutUnit units() const
Returns the units for the point.
void setY(const double y)
Sets y coordinate of point.
void flagsChanged(QgsLayoutRenderContext::Flags flags)
Emitted whenever the context's flags change.
@ FlagDebug
Debug/testing mode, items are drawn as solid rectangles.
@ FlagUseAdvancedEffects
Enable advanced effects such as blend modes.
@ FlagLosslessImageRendering
Render images losslessly whenever possible, instead of the default lossy jpeg rendering used for some...
@ FlagAntialiasing
Use antialiasing when drawing items.
@ FlagForceVectorOutput
Force output in vector format where possible, even if items require rasterization to keep their corre...
This class provides a method of storing sizes, consisting of a width and height, for use in QGIS layo...
static QgsLayoutSize decodeSize(const QString &string)
Decodes a size from a string.
double height() const
Returns the height of the size.
void setWidth(const double width)
Sets the width for the size.
Qgis::LayoutUnit units() const
Returns the units for the size.
double width() const
Returns the width of the size.
QString encodeSize() const
Encodes the layout size to a string.
void setHeight(const double height)
Sets the height for the size.
static QgsRenderContext createRenderContextForLayout(QgsLayout *layout, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout and painter destination.
static bool itemIsAClippingSource(const QgsLayoutItem *item)
Returns true if an item is a clipping item for another layout item.
static QgsLayoutItemPage::Orientation decodePaperOrientation(const QString &string, bool &ok)
Decodes a string representing a paper orientation and returns the decoded orientation.
static double normalizedAngle(double angle, bool allowNegative=false)
Ensures that an angle (in degrees) is in the range 0 <= angle < 360.
static Q_DECL_DEPRECATED double scaleFactorFromItemStyle(const QStyleOptionGraphicsItem *style)
Extracts the scale factor from an item style.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
@ ZItem
Minimum z value for items.
Qgis::LayoutUnit units() const
Returns the native units for the layout.
A named page size for layouts.
QgsLayoutSize size
Page size.
static Qgis::BlendMode getBlendModeEnum(QPainter::CompositionMode blendMode)
Returns a BlendMode corresponding to a QPainter::CompositionMode.
static QPainter::CompositionMode getCompositionMode(Qgis::BlendMode blendMode)
Returns a QPainter::CompositionMode corresponding to a BlendMode.
bool isActive(int key) const override
Returns true if the collection contains an active property with the specified key.
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.
QPainter * painter()
Returns the destination QPainter for the render operation.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
Scoped object for saving and restoring a QPainter object's state.
An interface for classes which can visit style entity (e.g.
QImage svgAsImage(const QString &path, double size, const QColor &fill, const QColor &stroke, double strokeWidth, double widthScaleFactor, bool &fitsInCache, double fixedAspectRatio=0, bool blocking=false, const QMap< QString, QString > ¶meters=QMap< QString, QString >())
Returns an SVG drawing as a QImage.
static Qt::PenJoinStyle decodePenJoinStyle(const QString &str)
static QPainter::CompositionMode decodeBlendMode(const QString &s)
static QString encodePenJoinStyle(Qt::PenJoinStyle style)
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)
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Contains details of a particular export layer relating to a layout item.