QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgslayoutitem.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgslayoutitem.cpp
3 -------------------
4 begin : June 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8/***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
17#include "qgslayoutitem.h"
18#include "moc_qgslayoutitem.cpp"
19#include "qgslayout.h"
20#include "qgslayoututils.h"
21#include "qgspagesizeregistry.h"
23#include "qgslayoutmodel.h"
24#include "qgssymbollayerutils.h"
25#include "qgslayoutitemgroup.h"
26#include "qgspainting.h"
27#include "qgslayoutundostack.h"
29#include "qgslayoutitempage.h"
30#include "qgsimageoperation.h"
33#include "qgssvgcache.h"
34
35#include <QPainter>
36#include <QStyleOptionGraphicsItem>
37#include <QUuid>
38
39#define CACHE_SIZE_LIMIT 5000
40
42 : mRenderContext( context )
43 , mViewScaleFactor( viewScaleFactor )
44{
45}
46
47
48
49QgsLayoutItem::QgsLayoutItem( QgsLayout *layout, bool manageZValue )
50 : QgsLayoutObject( layout )
51 , QGraphicsRectItem( nullptr )
52 , mUuid( QUuid::createUuid().toString() )
53{
54 setZValue( QgsLayout::ZItem );
55
56 // needed to access current view transform during paint operations
57 setFlags( flags() | QGraphicsItem::ItemUsesExtendedStyleOption | QGraphicsItem::ItemIsSelectable );
58
59 setCacheMode( QGraphicsItem::DeviceCoordinateCache );
60
61 //record initial position
63 mItemPosition = QgsLayoutPoint( scenePos().x(), scenePos().y(), initialUnits );
64 mItemSize = QgsLayoutSize( rect().width(), rect().height(), initialUnits );
65
66 // required to initially setup background/frame style
68 refreshFrame( false );
69
70 initConnectionsToLayout();
71
72 //let z-Value be managed by layout
73 if ( mLayout && manageZValue )
74 {
75 mLayoutManagesZValue = true;
76 mLayout->itemsModel()->addItemAtTop( this );
77 }
78 else
79 {
80 mLayoutManagesZValue = false;
81 }
82}
83
88
90{
91 if ( mLayout && mLayoutManagesZValue )
92 {
93 mLayout->itemsModel()->removeItem( this );
94 }
95}
96
98{
99 //return id, if it's not empty
100 if ( !id().isEmpty() )
101 {
102 return id();
103 }
104
105 //for unnamed items, default to item type
106 if ( QgsLayoutItemAbstractMetadata *metadata = QgsApplication::layoutItemRegistry()->itemMetadata( type() ) )
107 {
108 return tr( "<%1>" ).arg( metadata->visibleName() );
109 }
110
111 return tr( "<item>" );
112}
113
118
120{
121 return QgsApplication::getThemeIcon( QStringLiteral( "/mLayoutItem.svg" ) );
122}
123
128
129void QgsLayoutItem::setId( const QString &id )
130{
131 if ( id == mId )
132 {
133 return;
134 }
135
136 if ( !shouldBlockUndoCommands() )
137 mLayout->undoStack()->beginCommand( this, tr( "Change Item ID" ) );
138
139 mId = id;
140
141 if ( !shouldBlockUndoCommands() )
142 mLayout->undoStack()->endCommand();
143
144 setToolTip( id );
145
146 //inform model that id data has changed
147 if ( mLayout )
148 {
149 mLayout->itemsModel()->updateItemDisplayName( this );
150 }
151
152 emit changed();
153}
154
155void QgsLayoutItem::setSelected( bool selected )
156{
157 QGraphicsRectItem::setSelected( selected );
158 //inform model that id data has changed
159 if ( mLayout )
160 {
161 mLayout->itemsModel()->updateItemSelectStatus( this );
162 }
163}
164
165void QgsLayoutItem::setVisibility( const bool visible )
166{
167 if ( visible == isVisible() )
168 {
169 //nothing to do
170 return;
171 }
172
173 std::unique_ptr< QgsAbstractLayoutUndoCommand > command;
174 if ( !shouldBlockUndoCommands() )
175 {
176 command.reset( createCommand( visible ? tr( "Show Item" ) : tr( "Hide Item" ), 0 ) );
177 command->saveBeforeState();
178 }
179
180 QGraphicsItem::setVisible( visible );
181
182 if ( command )
183 {
184 command->saveAfterState();
185 mLayout->undoStack()->push( command.release() );
186 }
187
188 //inform model that visibility has changed
189 if ( mLayout )
190 {
191 mLayout->itemsModel()->updateItemVisibility( this );
192 }
193}
194
195void QgsLayoutItem::setLocked( const bool locked )
196{
197 if ( locked == mIsLocked )
198 {
199 return;
200 }
201
202 if ( !shouldBlockUndoCommands() )
203 mLayout->undoStack()->beginCommand( this, locked ? tr( "Lock Item" ) : tr( "Unlock Item" ) );
204
205 mIsLocked = locked;
206
207 if ( !shouldBlockUndoCommands() )
208 mLayout->undoStack()->endCommand();
209
210 //inform model that id data has changed
211 if ( mLayout )
212 {
213 mLayout->itemsModel()->updateItemLockStatus( this );
214 }
215
216 update();
217 emit lockChanged();
218}
219
221{
222 return !mParentGroupUuid.isEmpty() && mLayout && static_cast< bool >( mLayout->itemByUuid( mParentGroupUuid ) );
223}
224
226{
227 if ( !mLayout || mParentGroupUuid.isEmpty() )
228 return nullptr;
229
230 return qobject_cast< QgsLayoutItemGroup * >( mLayout->itemByUuid( mParentGroupUuid ) );
231}
232
234{
235 if ( !group )
236 mParentGroupUuid.clear();
237 else
238 mParentGroupUuid = group->uuid();
239 setFlag( QGraphicsItem::ItemIsSelectable, !static_cast< bool>( group ) ); //item in groups cannot be selected
240}
241
246
248{
249 return 0;
250}
251
256
261
263{
265 if ( !mLayout || mLayout->renderContext().currentExportLayer() == -1 )
266 return false;
267
268 // QGIS 4- return false from base class implementation
269
270 const int layers = numberExportLayers();
271 return mLayout->renderContext().currentExportLayer() < layers;
273}
274
279
280void QgsLayoutItem::paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget * )
281{
282 if ( !painter || !painter->device() || !shouldDrawItem() )
283 {
284 return;
285 }
286
287 if ( shouldDrawDebugRect() )
288 {
289 drawDebugRect( painter );
290 return;
291 }
292
293 const bool previewRender = !mLayout || mLayout->renderContext().isPreviewRender();
294 double destinationDpi = previewRender ? QgsLayoutUtils::scaleFactorFromItemStyle( itemStyle, painter ) * 25.4 : mLayout->renderContext().dpi();
295 const bool useImageCache = false;
296 bool forceRasterOutput = containsAdvancedEffects();
297 QPainter::CompositionMode blendMode = blendModeForRender();
298 if ( mLayout->renderContext().flags() & QgsLayoutRenderContext::FlagForceVectorOutput )
299 {
300 // the FlagForceVectorOutput flag overrides everything, and absolutely DISABLES rasterisation
301 // even when we need it to get correct rendering of opacity/blend modes/etc
302 forceRasterOutput = false;
303 }
304 else if ( blendMode != QPainter::CompositionMode_SourceOver )
305 {
306 // we have to rasterize content in order to show it with alternative blend modes
307 forceRasterOutput = true;
308 }
309
310 if ( useImageCache || forceRasterOutput )
311 {
312 double widthInPixels = 0;
313 double heightInPixels = 0;
314
315 if ( previewRender )
316 {
317 widthInPixels = boundingRect().width() * QgsLayoutUtils::scaleFactorFromItemStyle( itemStyle, painter );
318 heightInPixels = boundingRect().height() * QgsLayoutUtils::scaleFactorFromItemStyle( itemStyle, painter );
319 }
320 else
321 {
322 const double layoutUnitsToPixels = mLayout ? mLayout->convertFromLayoutUnits( 1, Qgis::LayoutUnit::Pixels ).length() : destinationDpi / 25.4;
323 widthInPixels = boundingRect().width() * layoutUnitsToPixels;
324 heightInPixels = boundingRect().height() * layoutUnitsToPixels;
325 }
326
327 // limit size of image for better performance
328 if ( previewRender && ( widthInPixels > CACHE_SIZE_LIMIT || heightInPixels > CACHE_SIZE_LIMIT ) )
329 {
330 double scale = 1.0;
331 if ( widthInPixels > heightInPixels )
332 {
333 scale = widthInPixels / CACHE_SIZE_LIMIT;
334 widthInPixels = CACHE_SIZE_LIMIT;
335 heightInPixels /= scale;
336 }
337 else
338 {
339 scale = heightInPixels / CACHE_SIZE_LIMIT;
340 heightInPixels = CACHE_SIZE_LIMIT;
341 widthInPixels /= scale;
342 }
343 destinationDpi = destinationDpi / scale;
344 }
345
346 if ( previewRender && !mItemCachedImage.isNull() && qgsDoubleNear( mItemCacheDpi, destinationDpi ) )
347 {
348 // can reuse last cached image
349 const QgsRenderContext context = QgsLayoutUtils::createRenderContextForLayout( mLayout, painter, destinationDpi );
350 const QgsScopedQPainterState painterState( painter );
351 preparePainter( painter );
352 const double cacheScale = destinationDpi / mItemCacheDpi;
353 painter->scale( cacheScale / context.scaleFactor(), cacheScale / context.scaleFactor() );
354 painter->setCompositionMode( blendMode );
355 painter->drawImage( boundingRect().x() * context.scaleFactor() / cacheScale,
356 boundingRect().y() * context.scaleFactor() / cacheScale, mItemCachedImage );
357 return;
358 }
359 else
360 {
361 QImage image = QImage( widthInPixels, heightInPixels, QImage::Format_ARGB32 );
362 image.fill( Qt::transparent );
363 image.setDotsPerMeterX( 1000 * destinationDpi * 25.4 );
364 image.setDotsPerMeterY( 1000 * destinationDpi * 25.4 );
365 QPainter p( &image );
366
367 preparePainter( &p );
370 // painter is already scaled to dots
371 // need to translate so that item origin is at 0,0 in painter coordinates (not bounding rect origin)
372 p.translate( -boundingRect().x() * context.scaleFactor(), -boundingRect().y() * context.scaleFactor() );
373 // scale to layout units for background and frame rendering
374 p.scale( context.scaleFactor(), context.scaleFactor() );
375 drawBackground( context );
376 p.scale( 1 / context.scaleFactor(), 1 / context.scaleFactor() );
377 const double viewScale = QgsLayoutUtils::scaleFactorFromItemStyle( itemStyle, painter );
378 QgsLayoutItemRenderContext itemRenderContext( context, viewScale );
379 draw( itemRenderContext );
380 p.scale( context.scaleFactor(), context.scaleFactor() );
381 drawFrame( context );
382 p.scale( 1 / context.scaleFactor(), 1 / context.scaleFactor() );
383 p.end();
384
385 QgsImageOperation::multiplyOpacity( image, mEvaluatedOpacity );
386
387 const QgsScopedQPainterState painterState( painter );
388 // scale painter from mm to dots
389 painter->scale( 1.0 / context.scaleFactor(), 1.0 / context.scaleFactor() );
390 painter->setCompositionMode( blendMode );
391 painter->drawImage( boundingRect().x() * context.scaleFactor(),
392 boundingRect().y() * context.scaleFactor(), image );
393
394 if ( previewRender )
395 {
396 mItemCacheDpi = destinationDpi;
397 mItemCachedImage = image;
398 }
399 }
400 }
401 else
402 {
403 // no caching or flattening
404 const QgsScopedQPainterState painterState( painter );
405 preparePainter( painter );
406 QgsRenderContext context = QgsLayoutUtils::createRenderContextForLayout( mLayout, painter, destinationDpi );
408 drawBackground( context );
409
410 const double viewScale = QgsLayoutUtils::scaleFactorFromItemStyle( itemStyle, painter );
411
412 // scale painter from mm to dots
413 painter->scale( 1.0 / context.scaleFactor(), 1.0 / context.scaleFactor() );
414 QgsLayoutItemRenderContext itemRenderContext( context, viewScale );
415 draw( itemRenderContext );
416
417 painter->scale( context.scaleFactor(), context.scaleFactor() );
418 drawFrame( context );
419 }
420
421 if ( isRefreshing() && previewRender )
422 {
423 drawRefreshingOverlay( painter, itemStyle );
424 }
425}
426
428{
429 if ( point == mReferencePoint )
430 {
431 return;
432 }
433
434 mReferencePoint = point;
435
436 //also need to adjust stored position
437 updateStoredItemPosition();
439}
440
441void QgsLayoutItem::attemptResize( const QgsLayoutSize &s, bool includesFrame )
442{
443 if ( !mLayout )
444 {
445 mItemSize = s;
446 setRect( 0, 0, s.width(), s.height() );
447 return;
448 }
449
450 QgsLayoutSize size = s;
451
452 if ( includesFrame )
453 {
454 //adjust position to account for frame size
455 const double bleed = mLayout->convertFromLayoutUnits( estimatedFrameBleed(), size.units() ).length();
456 size.setWidth( size.width() - 2 * bleed );
457 size.setHeight( size.height() - 2 * bleed );
458 }
459
460 const QgsLayoutSize evaluatedSize = applyDataDefinedSize( size );
461 const QSizeF targetSizeLayoutUnits = mLayout->convertToLayoutUnits( evaluatedSize );
462 QSizeF actualSizeLayoutUnits = applyMinimumSize( targetSizeLayoutUnits );
463 actualSizeLayoutUnits = applyFixedSize( actualSizeLayoutUnits );
464 actualSizeLayoutUnits = applyItemSizeConstraint( actualSizeLayoutUnits );
465
466 if ( actualSizeLayoutUnits == rect().size() )
467 {
468 return;
469 }
470
471 const QgsLayoutSize actualSizeTargetUnits = mLayout->convertFromLayoutUnits( actualSizeLayoutUnits, size.units() );
472 mItemSize = actualSizeTargetUnits;
473
474 setRect( 0, 0, actualSizeLayoutUnits.width(), actualSizeLayoutUnits.height() );
476 emit sizePositionChanged();
477}
478
479void QgsLayoutItem::attemptMove( const QgsLayoutPoint &p, bool useReferencePoint, bool includesFrame, int page )
480{
481 if ( !mLayout )
482 {
483 mItemPosition = p;
484 setPos( p.toQPointF() );
485 return;
486 }
487
488 QgsLayoutPoint point = p;
489 if ( page >= 0 )
490 {
491 point = mLayout->pageCollection()->pagePositionToAbsolute( page, p );
492 }
493
494 if ( includesFrame )
495 {
496 //adjust position to account for frame size
497 const double bleed = mLayout->convertFromLayoutUnits( estimatedFrameBleed(), point.units() ).length();
498 point.setX( point.x() + bleed );
499 point.setY( point.y() + bleed );
500 }
501
502 QgsLayoutPoint evaluatedPoint = point;
503 if ( !useReferencePoint )
504 {
505 evaluatedPoint = topLeftToReferencePoint( point );
506 }
507
508 evaluatedPoint = applyDataDefinedPosition( evaluatedPoint );
509 const QPointF evaluatedPointLayoutUnits = mLayout->convertToLayoutUnits( evaluatedPoint );
510 const QPointF topLeftPointLayoutUnits = adjustPointForReferencePosition( evaluatedPointLayoutUnits, rect().size(), mReferencePoint );
511 if ( topLeftPointLayoutUnits == scenePos() && point.units() == mItemPosition.units() )
512 {
513 //TODO - add test for second condition
514 return;
515 }
516
517 const QgsLayoutPoint referencePointTargetUnits = mLayout->convertFromLayoutUnits( evaluatedPointLayoutUnits, point.units() );
518 mItemPosition = referencePointTargetUnits;
519 setScenePos( topLeftPointLayoutUnits );
520 emit sizePositionChanged();
521}
522
523void QgsLayoutItem::attemptSetSceneRect( const QRectF &rect, bool includesFrame )
524{
525 const QPointF newPos = rect.topLeft();
526
527 blockSignals( true );
528 // translate new size to current item units
529 const QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( rect.size(), mItemSize.units() );
530 attemptResize( newSize, includesFrame );
531
532 // translate new position to current item units
533 const QgsLayoutPoint itemPos = mLayout->convertFromLayoutUnits( newPos, mItemPosition.units() );
534 attemptMove( itemPos, false, includesFrame );
535 blockSignals( false );
536 emit sizePositionChanged();
537}
538
539void QgsLayoutItem::attemptMoveBy( double deltaX, double deltaY )
540{
541 if ( !mLayout )
542 {
543 moveBy( deltaX, deltaY );
544 return;
545 }
546
548 const QgsLayoutPoint deltaPos = mLayout->convertFromLayoutUnits( QPointF( deltaX, deltaY ), itemPos.units() );
549 itemPos.setX( itemPos.x() + deltaPos.x() );
550 itemPos.setY( itemPos.y() + deltaPos.y() );
551 attemptMove( itemPos );
552}
553
555{
556 if ( !mLayout )
557 return -1;
558
559 return mLayout->pageCollection()->pageNumberForPoint( pos() );
560}
561
563{
564 QPointF p = positionAtReferencePoint( mReferencePoint );
565
566 if ( !mLayout )
567 return p;
568
569 // try to get page
570 QgsLayoutItemPage *pageItem = mLayout->pageCollection()->page( page() );
571 if ( !pageItem )
572 return p;
573
574 p.ry() -= pageItem->pos().y();
575 return p;
576}
577
579{
580 const QPointF p = pagePos();
581 if ( !mLayout )
582 return QgsLayoutPoint( p );
583
584 return mLayout->convertFromLayoutUnits( p, mItemPosition.units() );
585}
586
587void QgsLayoutItem::setScenePos( const QPointF destinationPos )
588{
589 //since setPos does not account for item rotation, use difference between
590 //current scenePos (which DOES account for rotation) and destination pos
591 //to calculate how much the item needs to move
592 if ( auto *lParentItem = parentItem() )
593 setPos( pos() + ( destinationPos - scenePos() ) + lParentItem->scenePos() );
594 else
595 setPos( pos() + ( destinationPos - scenePos() ) );
596}
597
598bool QgsLayoutItem::shouldBlockUndoCommands() const
599{
600 return !mLayout || mLayout != scene() || mBlockUndoCommands;
601}
602
604{
606 return false;
607
608 if ( !mLayout || mLayout->renderContext().isPreviewRender() )
609 {
610 //preview mode so OK to draw item
611 return true;
612 }
613
614 //exporting layout, so check if item is excluded from exports
615 return !mEvaluatedExcludeFromExports;
616}
617
619{
620 return mItemRotation;
621}
622
623bool QgsLayoutItem::writeXml( QDomElement &parentElement, QDomDocument &doc, const QgsReadWriteContext &context ) const
624{
625 QDomElement element = doc.createElement( QStringLiteral( "LayoutItem" ) );
626 element.setAttribute( QStringLiteral( "type" ), QString::number( type() ) );
627
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() );
633 element.setAttribute( QStringLiteral( "positionOnPage" ), pagePositionWithUnits().encodePoint() );
634 element.setAttribute( QStringLiteral( "size" ), mItemSize.encodeSize() );
635 element.setAttribute( QStringLiteral( "itemRotation" ), QString::number( mItemRotation ) );
636 element.setAttribute( QStringLiteral( "groupUuid" ), mParentGroupUuid );
637
638 element.setAttribute( QStringLiteral( "zValue" ), QString::number( zValue() ) );
639 element.setAttribute( QStringLiteral( "visibility" ), isVisible() );
640 //position lock for mouse moves/resizes
641 if ( mIsLocked )
642 {
643 element.setAttribute( QStringLiteral( "positionLock" ), QStringLiteral( "true" ) );
644 }
645 else
646 {
647 element.setAttribute( QStringLiteral( "positionLock" ), QStringLiteral( "false" ) );
648 }
649
650 //frame
651 if ( mFrame )
652 {
653 element.setAttribute( QStringLiteral( "frame" ), QStringLiteral( "true" ) );
654 }
655 else
656 {
657 element.setAttribute( QStringLiteral( "frame" ), QStringLiteral( "false" ) );
658 }
659
660 //background
661 if ( mBackground )
662 {
663 element.setAttribute( QStringLiteral( "background" ), QStringLiteral( "true" ) );
664 }
665 else
666 {
667 element.setAttribute( QStringLiteral( "background" ), QStringLiteral( "false" ) );
668 }
669
670 //frame color
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() );
678 element.setAttribute( QStringLiteral( "frameJoinStyle" ), QgsSymbolLayerUtils::encodePenJoinStyle( mFrameJoinStyle ) );
679
680 //background color
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 );
687
688 //blend mode
689 element.setAttribute( QStringLiteral( "blendMode" ), static_cast< int >( QgsPainting::getBlendModeEnum( mBlendMode ) ) );
690
691 //opacity
692 element.setAttribute( QStringLiteral( "opacity" ), QString::number( mOpacity ) );
693
694 element.setAttribute( QStringLiteral( "excludeFromExports" ), mExcludeFromExports );
695
696 writeObjectPropertiesToElement( element, doc, context );
697
698 writePropertiesToElement( element, doc, context );
699 parentElement.appendChild( element );
700
701 return true;
702}
703
704bool QgsLayoutItem::readXml( const QDomElement &element, const QDomDocument &doc, const QgsReadWriteContext &context )
705{
706 if ( element.nodeName() != QLatin1String( "LayoutItem" ) )
707 {
708 return false;
709 }
710
711 readObjectPropertiesFromElement( element, doc, context );
712
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() );
718 attemptMove( QgsLayoutPoint::decodePoint( element.attribute( QStringLiteral( "position" ) ) ) );
719 attemptResize( QgsLayoutSize::decodeSize( element.attribute( QStringLiteral( "size" ) ) ) );
720
721 mParentGroupUuid = element.attribute( QStringLiteral( "groupUuid" ) );
722 if ( !mParentGroupUuid.isEmpty() )
723 {
724 if ( QgsLayoutItemGroup *group = parentGroup() )
725 {
726 group->addItem( this );
727 }
728 }
729 mTemplateUuid = element.attribute( QStringLiteral( "templateUuid" ) );
730
731 //position lock for mouse moves/resizes
732 const QString positionLock = element.attribute( QStringLiteral( "positionLock" ) );
733 if ( positionLock.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 )
734 {
735 setLocked( true );
736 }
737 else
738 {
739 setLocked( false );
740 }
741 //visibility
742 setVisibility( element.attribute( QStringLiteral( "visibility" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) );
743 setZValue( element.attribute( QStringLiteral( "zValue" ) ).toDouble() );
744
745 //frame
746 const QString frame = element.attribute( QStringLiteral( "frame" ) );
747 if ( frame.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 )
748 {
749 mFrame = true;
750 }
751 else
752 {
753 mFrame = false;
754 }
755
756 //frame
757 const QString background = element.attribute( QStringLiteral( "background" ) );
758 if ( background.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 )
759 {
760 mBackground = true;
761 }
762 else
763 {
764 mBackground = false;
765 }
766
767 //pen
768 mFrameWidth = QgsLayoutMeasurement::decodeMeasurement( element.attribute( QStringLiteral( "outlineWidthM" ) ) );
769 mFrameJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( element.attribute( QStringLiteral( "frameJoinStyle" ), QStringLiteral( "miter" ) ) );
770 const QDomNodeList frameColorList = element.elementsByTagName( QStringLiteral( "FrameColor" ) );
771 if ( !frameColorList.isEmpty() )
772 {
773 const QDomElement frameColorElem = frameColorList.at( 0 ).toElement();
774 bool redOk = false;
775 bool greenOk = false;
776 bool blueOk = false;
777 bool alphaOk = false;
778 int penRed, penGreen, penBlue, penAlpha;
779
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 );
784
785 if ( redOk && greenOk && blueOk && alphaOk )
786 {
787 mFrameColor = QColor( penRed, penGreen, penBlue, penAlpha );
788 }
789 }
790 refreshFrame( false );
791
792 //brush
793 const QDomNodeList bgColorList = element.elementsByTagName( QStringLiteral( "BackgroundColor" ) );
794 if ( !bgColorList.isEmpty() )
795 {
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 )
804 {
805 mBackgroundColor = QColor( bgRed, bgGreen, bgBlue, bgAlpha );
806 setBrush( QBrush( mBackgroundColor, Qt::SolidPattern ) );
807 }
808 //apply any data defined settings
809 refreshBackgroundColor( false );
810 }
811
812 //blend mode
813 setBlendMode( QgsPainting::getCompositionMode( static_cast< Qgis::BlendMode >( element.attribute( QStringLiteral( "blendMode" ), QStringLiteral( "0" ) ).toUInt() ) ) );
814
815 //opacity
816 if ( element.hasAttribute( QStringLiteral( "opacity" ) ) )
817 {
818 setItemOpacity( element.attribute( QStringLiteral( "opacity" ), QStringLiteral( "1" ) ).toDouble() );
819 }
820 else
821 {
822 setItemOpacity( 1.0 - element.attribute( QStringLiteral( "transparency" ), QStringLiteral( "0" ) ).toInt() / 100.0 );
823 }
824
825 mExcludeFromExports = element.attribute( QStringLiteral( "excludeFromExports" ), QStringLiteral( "0" ) ).toInt();
826 mEvaluatedExcludeFromExports = mExcludeFromExports;
827
828 const bool result = readPropertiesFromElement( element, doc, context );
829
830 mBlockUndoCommands = false;
831
832 emit changed();
833 update();
834 return result;
835}
836
840
841QgsAbstractLayoutUndoCommand *QgsLayoutItem::createCommand( const QString &text, int id, QUndoCommand *parent )
842{
843 return new QgsLayoutItemUndoCommand( this, text, id, parent );
844}
845
846void QgsLayoutItem::setFrameEnabled( bool drawFrame )
847{
848 if ( drawFrame == mFrame )
849 {
850 //no change
851 return;
852 }
853
854 mFrame = drawFrame;
855 refreshFrame( true );
856 emit frameChanged();
857}
858
859void QgsLayoutItem::setFrameStrokeColor( const QColor &color )
860{
861 if ( mFrameColor == color )
862 {
863 //no change
864 return;
865 }
866 mFrameColor = color;
867 // apply any datadefined overrides
868 refreshFrame( true );
869 emit frameChanged();
870}
871
873{
874 if ( mFrameWidth == width )
875 {
876 //no change
877 return;
878 }
879 mFrameWidth = width;
880 refreshFrame();
881 emit frameChanged();
882}
883
884void QgsLayoutItem::setFrameJoinStyle( const Qt::PenJoinStyle style )
885{
886 if ( mFrameJoinStyle == style )
887 {
888 //no change
889 return;
890 }
891 mFrameJoinStyle = style;
892
893 QPen itemPen = pen();
894 itemPen.setJoinStyle( mFrameJoinStyle );
895 setPen( itemPen );
896 emit frameChanged();
897}
898
899void QgsLayoutItem::setBackgroundEnabled( bool drawBackground )
900{
901 mBackground = drawBackground;
902 update();
903}
904
905void QgsLayoutItem::setBackgroundColor( const QColor &color )
906{
907 mBackgroundColor = color;
908 // apply any datadefined overrides
910}
911
912void QgsLayoutItem::setBlendMode( const QPainter::CompositionMode mode )
913{
914 mBlendMode = mode;
915 // Update the item effect to use the new blend mode
917 update();
918}
919
920void QgsLayoutItem::setItemOpacity( double opacity )
921{
922 mOpacity = opacity;
923 refreshOpacity( mItemCachedImage.isNull() );
924 if ( !mItemCachedImage.isNull() )
926}
927
929{
930 return mExcludeFromExports;
931}
932
938
940{
941 return itemFlags() & Flag::FlagOverridesPaint ? false : mEvaluatedOpacity < 1.0;
942}
943
945{
946 return ( itemFlags() & Flag::FlagOverridesPaint && itemOpacity() < 1.0 ) ||
947 blendMode() != QPainter::CompositionMode_SourceOver;
948}
949
951{
952 if ( !frameEnabled() )
953 {
954 return 0;
955 }
956
957 return pen().widthF() / 2.0;
958}
959
961{
962 const double frameBleed = estimatedFrameBleed();
963 return rect().adjusted( -frameBleed, -frameBleed, frameBleed, frameBleed );
964}
965
966void QgsLayoutItem::moveContent( double, double )
967{
968
969}
970
972{
973
974}
975
976void QgsLayoutItem::zoomContent( double, QPointF )
977{
978
979}
980
981void QgsLayoutItem::beginCommand( const QString &commandText, UndoCommand command )
982{
983 if ( !mLayout )
984 return;
985
986 mLayout->undoStack()->beginCommand( this, commandText, command );
987}
988
990{
991 if ( mLayout )
992 mLayout->undoStack()->endCommand();
993}
994
996{
997 if ( mLayout )
998 mLayout->undoStack()->cancelCommand();
999}
1000
1001QgsLayoutPoint QgsLayoutItem::applyDataDefinedPosition( const QgsLayoutPoint &position )
1002{
1003 if ( !mLayout )
1004 {
1005 return position;
1006 }
1007
1009 const double evaluatedX = mDataDefinedProperties.valueAsDouble( QgsLayoutObject::DataDefinedProperty::PositionX, context, position.x() );
1010 const double evaluatedY = mDataDefinedProperties.valueAsDouble( QgsLayoutObject::DataDefinedProperty::PositionY, context, position.y() );
1011 return QgsLayoutPoint( evaluatedX, evaluatedY, position.units() );
1012}
1013
1014void QgsLayoutItem::applyDataDefinedOrientation( double &width, double &height, const QgsExpressionContext &context )
1015{
1016 bool ok = false;
1017 const QString orientationString = mDataDefinedProperties.valueAsString( QgsLayoutObject::DataDefinedProperty::PaperOrientation, context, QString(), &ok );
1018 if ( ok && !orientationString.isEmpty() )
1019 {
1020 const QgsLayoutItemPage::Orientation orientation = QgsLayoutUtils::decodePaperOrientation( orientationString, ok );
1021 if ( ok )
1022 {
1023 double heightD = 0.0, widthD = 0.0;
1024 switch ( orientation )
1025 {
1027 {
1028 heightD = std::max( height, width );
1029 widthD = std::min( height, width );
1030 break;
1031 }
1033 {
1034 heightD = std::min( height, width );
1035 widthD = std::max( height, width );
1036 break;
1037 }
1038 }
1039 width = widthD;
1040 height = heightD;
1041 }
1042 }
1043}
1044
1046{
1047 if ( !mLayout )
1048 {
1049 return size;
1050 }
1051
1056 return size;
1057
1058
1060
1061 // lowest priority is page size
1063 QgsPageSize matchedSize;
1064 double evaluatedWidth = size.width();
1065 double evaluatedHeight = size.height();
1066 if ( QgsApplication::pageSizeRegistry()->decodePageSize( pageSize, matchedSize ) )
1067 {
1068 const QgsLayoutSize convertedSize = mLayout->renderContext().measurementConverter().convert( matchedSize.size, size.units() );
1069 evaluatedWidth = convertedSize.width();
1070 evaluatedHeight = convertedSize.height();
1071 }
1072
1073 // highest priority is dd width/height
1075 evaluatedHeight = mDataDefinedProperties.valueAsDouble( QgsLayoutObject::DataDefinedProperty::ItemHeight, context, evaluatedHeight );
1076
1077 //which is finally overwritten by data defined orientation
1078 applyDataDefinedOrientation( evaluatedWidth, evaluatedHeight, context );
1079
1080 return QgsLayoutSize( evaluatedWidth, evaluatedHeight, size.units() );
1081}
1082
1083QPainter::CompositionMode QgsLayoutItem::blendModeForRender() const
1084{
1085 QPainter::CompositionMode mode = mEvaluatedBlendMode;
1086 if ( !( mLayout->renderContext().flags() & QgsLayoutRenderContext::FlagUseAdvancedEffects ) )
1087 {
1088 // advanced effects disabled, reset blend mode
1089 mode = QPainter::CompositionMode_SourceOver;
1090 }
1091
1092 if ( mLayout->renderContext().flags() & QgsLayoutRenderContext::FlagForceVectorOutput )
1093 {
1094 // the FlagForceVectorOutput flag overrides everything, and absolutely DISABLES rasterisation
1095 // even when we need it to get correct rendering of opacity/blend modes/etc
1096 mode = QPainter::CompositionMode_SourceOver;
1097 }
1098 return mode;
1099}
1100
1101double QgsLayoutItem::applyDataDefinedRotation( const double rotation )
1102{
1103 if ( !mLayout )
1104 {
1105 return rotation;
1106 }
1107
1109 const double evaluatedRotation = mDataDefinedProperties.valueAsDouble( QgsLayoutObject::DataDefinedProperty::ItemRotation, context, rotation );
1110 return evaluatedRotation;
1111}
1112
1114{
1115 //update data defined properties and update item to match
1116
1117 //evaluate width and height first, since they may affect position if non-top-left reference point set
1120 {
1122 }
1125 {
1127 }
1129 {
1131 }
1133 {
1134 refreshOpacity( false );
1135 }
1137 {
1138 refreshFrame( false );
1139 }
1141 {
1142 refreshBackgroundColor( false );
1143 }
1145 {
1147 }
1149 {
1150 const bool exclude = mExcludeFromExports;
1151 //data defined exclude from exports set?
1153 }
1154
1155 update();
1156}
1157
1158void QgsLayoutItem::setItemRotation( double angle, const bool adjustPosition )
1159{
1160 if ( angle >= 360.0 || angle <= -360.0 )
1161 {
1162 angle = std::fmod( angle, 360.0 );
1163 }
1164
1165 const QPointF point = adjustPosition ? positionAtReferencePoint( QgsLayoutItem::Middle )
1166 : pos();
1167 const double rotationRequired = angle - rotation();
1168 rotateItem( rotationRequired, point );
1169
1170 mItemRotation = angle;
1171}
1172
1173void QgsLayoutItem::updateStoredItemPosition()
1174{
1175 const QPointF layoutPosReferencePoint = positionAtReferencePoint( mReferencePoint );
1176 mItemPosition = mLayout->convertFromLayoutUnits( layoutPosReferencePoint, mItemPosition.units() );
1177}
1178
1179void QgsLayoutItem::rotateItem( const double angle, const QPointF transformOrigin )
1180{
1181 double evaluatedAngle = angle + rotation();
1182 evaluatedAngle = QgsLayoutUtils::normalizedAngle( evaluatedAngle, true );
1183 mItemRotation = evaluatedAngle;
1184
1185 QPointF itemTransformOrigin = mapFromScene( transformOrigin );
1186
1187 refreshItemRotation( &itemTransformOrigin );
1188}
1189
1191{
1192 return false;
1193}
1194
1201
1203{
1204 Q_UNUSED( visitor );
1205 return true;
1206}
1207
1209{
1210 return QgsGeometry();
1211}
1212
1220
1222{
1223 if ( !mItemCachedImage.isNull() )
1224 {
1225 mItemCachedImage = QImage();
1226 mItemCacheDpi = -1;
1227 update();
1228 }
1229}
1230
1232{
1233 update();
1234}
1235
1236void QgsLayoutItem::drawDebugRect( QPainter *painter )
1237{
1238 if ( !painter )
1239 {
1240 return;
1241 }
1242
1243 const QgsScopedQPainterState painterState( painter );
1244 painter->setRenderHint( QPainter::Antialiasing, false );
1245 painter->setPen( Qt::NoPen );
1246 painter->setBrush( QColor( 100, 255, 100, 200 ) );
1247 painter->drawRect( rect() );
1248}
1249
1250QPainterPath QgsLayoutItem::framePath() const
1251{
1252 QPainterPath path;
1253 path.addRect( QRectF( 0, 0, rect().width(), rect().height() ) );
1254 return path;
1255}
1256
1258{
1259 if ( !mFrame || !context.painter() )
1260 return;
1261
1262 QPainter *p = context.painter();
1263
1264 const QgsScopedQPainterState painterState( p );
1265
1266 p->setPen( pen() );
1267 p->setBrush( Qt::NoBrush );
1268 context.setPainterFlagsUsingContext( p );
1269
1270 p->drawPath( framePath() );
1271}
1272
1274{
1275 if ( !mBackground || !context.painter() )
1276 return;
1277
1278 const QgsScopedQPainterState painterState( context.painter() );
1279
1280 QPainter *p = context.painter();
1281 p->setBrush( brush() );
1282 p->setPen( Qt::NoPen );
1283 context.setPainterFlagsUsingContext( p );
1284
1285 p->drawPath( framePath() );
1286}
1287
1288void QgsLayoutItem::drawRefreshingOverlay( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle )
1289{
1290 const QgsScopedQPainterState painterState( painter );
1291 bool fitsInCache = false;
1292 const int xSize = std::floor( static_cast<double>( QFontMetrics( QFont() ).horizontalAdvance( 'X' ) ) * painter->device()->devicePixelRatioF() );
1293 const QImage refreshingImage = QgsApplication::svgCache()->svgAsImage( QStringLiteral( ":/images/composer/refreshing_item.svg" ), xSize * 3, QColor(), QColor(), 1, 1, fitsInCache );
1294
1295 const double previewScaleFactor = QgsLayoutUtils::scaleFactorFromItemStyle( itemStyle, painter );
1296 painter->scale( 1.0 / previewScaleFactor / painter->device()->devicePixelRatioF(), 1.0 / previewScaleFactor / painter->device()->devicePixelRatioF() );
1297 painter->drawImage( xSize, xSize, refreshingImage );
1298}
1299
1301{
1302 mFixedSize = size;
1304}
1305
1307{
1308 mMinimumSize = size;
1310}
1311
1312QSizeF QgsLayoutItem::applyItemSizeConstraint( const QSizeF targetSize )
1313{
1314 return targetSize;
1315}
1316
1318{
1319 attemptResize( mItemSize );
1320}
1321
1323{
1324 attemptMove( mItemPosition );
1325}
1326
1327QPointF QgsLayoutItem::itemPositionAtReferencePoint( const ReferencePoint reference, const QSizeF size ) const
1328{
1329 switch ( reference )
1330 {
1331 case UpperMiddle:
1332 return QPointF( size.width() / 2.0, 0 );
1333 case UpperRight:
1334 return QPointF( size.width(), 0 );
1335 case MiddleLeft:
1336 return QPointF( 0, size.height() / 2.0 );
1337 case Middle:
1338 return QPointF( size.width() / 2.0, size.height() / 2.0 );
1339 case MiddleRight:
1340 return QPointF( size.width(), size.height() / 2.0 );
1341 case LowerLeft:
1342 return QPointF( 0, size.height() );
1343 case LowerMiddle:
1344 return QPointF( size.width() / 2.0, size.height() );
1345 case LowerRight:
1346 return QPointF( size.width(), size.height() );
1347 case UpperLeft:
1348 return QPointF( 0, 0 );
1349 }
1350 // no warnings
1351 return QPointF( 0, 0 );
1352}
1353
1354QPointF QgsLayoutItem::adjustPointForReferencePosition( const QPointF position, const QSizeF size, const ReferencePoint reference ) const
1355{
1356 const QPointF itemPosition = mapFromScene( position ); //need to map from scene to handle item rotation
1357 const QPointF adjustedPointInsideItem = itemPosition - itemPositionAtReferencePoint( reference, size );
1358 return mapToScene( adjustedPointInsideItem );
1359}
1360
1362{
1363 const QPointF pointWithinItem = itemPositionAtReferencePoint( reference, rect().size() );
1364 return mapToScene( pointWithinItem );
1365}
1366
1368{
1369 const QPointF topLeft = mLayout->convertToLayoutUnits( point );
1370 const QPointF refPoint = topLeft + itemPositionAtReferencePoint( mReferencePoint, rect().size() );
1371 return mLayout->convertFromLayoutUnits( refPoint, point.units() );
1372}
1373
1374bool QgsLayoutItem::writePropertiesToElement( QDomElement &, QDomDocument &, const QgsReadWriteContext & ) const
1375{
1376 return true;
1377}
1378
1379bool QgsLayoutItem::readPropertiesFromElement( const QDomElement &, const QDomDocument &, const QgsReadWriteContext & )
1380{
1381
1382 return true;
1383}
1384
1385void QgsLayoutItem::initConnectionsToLayout()
1386{
1387 if ( !mLayout )
1388 return;
1389
1390}
1391
1392void QgsLayoutItem::preparePainter( QPainter *painter )
1393{
1394 if ( !painter || !painter->device() )
1395 {
1396 return;
1397 }
1398
1399 painter->setRenderHint( QPainter::Antialiasing, shouldDrawAntialiased() );
1400
1401 painter->setRenderHint( QPainter::LosslessImageRendering, mLayout && mLayout->renderContext().testFlag( QgsLayoutRenderContext::FlagLosslessImageRendering ) );
1402}
1403
1404bool QgsLayoutItem::shouldDrawAntialiased() const
1405{
1406 if ( !mLayout )
1407 {
1408 return true;
1409 }
1410 return mLayout->renderContext().testFlag( QgsLayoutRenderContext::FlagAntialiasing ) && !mLayout->renderContext().testFlag( QgsLayoutRenderContext::FlagDebug );
1411}
1412
1413bool QgsLayoutItem::shouldDrawDebugRect() const
1414{
1415 return mLayout && mLayout->renderContext().testFlag( QgsLayoutRenderContext::FlagDebug );
1416}
1417
1418QSizeF QgsLayoutItem::applyMinimumSize( const QSizeF targetSize )
1419{
1420 if ( !mLayout || minimumSize().isEmpty() )
1421 {
1422 return targetSize;
1423 }
1424 const QSizeF minimumSizeLayoutUnits = mLayout->convertToLayoutUnits( minimumSize() );
1425 return targetSize.expandedTo( minimumSizeLayoutUnits );
1426}
1427
1428QSizeF QgsLayoutItem::applyFixedSize( const QSizeF targetSize )
1429{
1430 if ( !mLayout || fixedSize().isEmpty() )
1431 {
1432 return targetSize;
1433 }
1434
1435 QSizeF size = targetSize;
1436 const QSizeF fixedSizeLayoutUnits = mLayout->convertToLayoutUnits( fixedSize() );
1437 if ( fixedSizeLayoutUnits.width() > 0 )
1438 size.setWidth( fixedSizeLayoutUnits.width() );
1439 if ( fixedSizeLayoutUnits.height() > 0 )
1440 size.setHeight( fixedSizeLayoutUnits.height() );
1441
1442 return size;
1443}
1444
1446{
1447 double r = mItemRotation;
1448
1449 //data defined rotation set?
1451
1452 if ( qgsDoubleNear( r, rotation() ) && !origin )
1453 {
1454 return;
1455 }
1456
1457 const QPointF transformPoint = origin ? *origin : mapFromScene( positionAtReferencePoint( QgsLayoutItem::Middle ) );
1458
1459 if ( !transformPoint.isNull() )
1460 {
1461 //adjustPosition set, so shift the position of the item so that rotation occurs around item center
1462 //create a line from the transform point to the item's origin, in scene coordinates
1463 QLineF refLine = QLineF( mapToScene( transformPoint ), mapToScene( QPointF( 0, 0 ) ) );
1464 //rotate this line by the current rotation angle
1465 refLine.setAngle( refLine.angle() - r + rotation() );
1466 //get new end point of line - this is the new item position
1467 const QPointF rotatedReferencePoint = refLine.p2();
1468 setPos( rotatedReferencePoint );
1469 }
1470
1471 setTransformOriginPoint( 0, 0 );
1472 QGraphicsItem::setRotation( r );
1473
1474 //adjust stored position of item to match scene pos of reference point
1475 updateStoredItemPosition();
1476 emit sizePositionChanged();
1477
1478 emit rotationChanged( r );
1479
1480 //update bounds of scene, since rotation may affect this
1481 mLayout->updateBounds();
1482}
1483
1484void QgsLayoutItem::refreshOpacity( bool updateItem )
1485{
1486 //data defined opacity set?
1488
1489 // Set the QGraphicItem's opacity
1490 mEvaluatedOpacity = opacity / 100.0;
1491
1493 {
1494 // item handles it's own painting, so it won't use the built-in opacity handling in QgsLayoutItem::paint, and
1495 // we have to rely on QGraphicsItem opacity to handle this
1496 setOpacity( mEvaluatedOpacity );
1497 }
1498
1499 if ( updateItem )
1500 {
1501 update();
1502 }
1503}
1504
1505void QgsLayoutItem::refreshFrame( bool updateItem )
1506{
1507 if ( !mFrame )
1508 {
1509 setPen( Qt::NoPen );
1510 return;
1511 }
1512
1513 //data defined stroke color set?
1514 bool ok = false;
1516 QPen itemPen;
1517 if ( ok )
1518 {
1519 itemPen = QPen( frameColor );
1520 }
1521 else
1522 {
1523 itemPen = QPen( mFrameColor );
1524 }
1525 itemPen.setJoinStyle( mFrameJoinStyle );
1526
1527 if ( mLayout )
1528 itemPen.setWidthF( mLayout->convertToLayoutUnits( mFrameWidth ) );
1529 else
1530 itemPen.setWidthF( mFrameWidth.length() );
1531
1532 setPen( itemPen );
1533
1534 if ( updateItem )
1535 {
1536 update();
1537 }
1538}
1539
1540QColor QgsLayoutItem::backgroundColor( bool useDataDefined ) const
1541{
1542 return useDataDefined ? brush().color() : mBackgroundColor;
1543}
1544
1545
1547{
1548 //data defined fill color set?
1549 bool ok = false;
1551 if ( ok )
1552 {
1553 setBrush( QBrush( backgroundColor, Qt::SolidPattern ) );
1554 }
1555 else
1556 {
1557 setBrush( QBrush( mBackgroundColor, Qt::SolidPattern ) );
1558 }
1559 if ( updateItem )
1560 {
1561 update();
1562 }
1563}
1564
1566{
1567 QPainter::CompositionMode blendMode = mBlendMode;
1568
1569 //data defined blend mode set?
1570 bool ok = false;
1572 if ( ok && !blendStr.isEmpty() )
1573 {
1574 const QString blendstr = blendStr.trimmed();
1575 const QPainter::CompositionMode blendModeD = QgsSymbolLayerUtils::decodeBlendMode( blendstr );
1576 blendMode = blendModeD;
1577 }
1578
1579 mEvaluatedBlendMode = blendMode;
1580
1581 // we can only enable caching if no blend mode is set -- otherwise
1582 // we need to redraw the item every time it is painted
1583 if ( mEvaluatedBlendMode == QPainter::CompositionMode_Source && !( itemFlags() & QgsLayoutItem::FlagDisableSceneCaching ) )
1584 setCacheMode( QGraphicsItem::DeviceCoordinateCache );
1585 else
1586 setCacheMode( QGraphicsItem::NoCache );
1587
1588 update();
1589}
1590
LayoutUnit
Layout measurement units.
Definition qgis.h:4867
@ Millimeters
Millimeters.
BlendMode
Blending modes defining the available composition modes that can be used when painting.
Definition qgis.h:4594
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.
Stores metadata about one layout item class.
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 refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::DataDefinedProperty::AllProperties)
Refreshes a data defined property for the item by reevaluating the property's value and redrawing the...
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.
@ 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.
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 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.
@ FlagDisableSceneCaching
Item should not have QGraphicsItem caching enabled.
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.
QFlags< Flag > Flags
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
QgsExpressionContext createExpressionContext() const override
Creates an expression context relating to the objects' current state.
DataDefinedProperty
Data defined properties for different item types.
@ ExcludeFromExports
Exclude item from exports.
@ PaperOrientation
Paper orientation.
@ BackgroundColor
Item background color.
@ PresetPaperSize
Preset paper size for composition.
@ AllProperties
All properties for item.
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.
@ 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.
Definition qgslayout.h:49
@ ZItem
Minimum z value for items.
Definition qgslayout.h:58
Qgis::LayoutUnit units() const
Returns the native units for the layout.
Definition qgslayout.h:329
A named page size for layouts.
QgsLayoutSize size
Page size.
static Qgis::BlendMode getBlendModeEnum(QPainter::CompositionMode blendMode)
Returns a Qgis::BlendMode corresponding to a QPainter::CompositionMode.
static QPainter::CompositionMode getCompositionMode(Qgis::BlendMode blendMode)
Returns a QPainter::CompositionMode corresponding to a Qgis::BlendMode.
bool isActive(int key) const final
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 > &parameters=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)
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:6535
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:6534
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:5958
#define CACHE_SIZE_LIMIT
Contains details of a particular export layer relating to a layout item.