38 #include <QStyleOptionGraphicsItem> 43 mBackgroundUpdateTimer =
new QTimer(
this );
44 mBackgroundUpdateTimer->setSingleShot(
true );
45 connect( mBackgroundUpdateTimer, &QTimer::timeout,
this, &QgsLayoutItemMap::recreateCachedImageInBackground );
49 setCacheMode( QGraphicsItem::NoCache );
56 mGridStack = qgis::make_unique< QgsLayoutItemMapGridStack >( this );
57 mOverviewStack = qgis::make_unique< QgsLayoutItemMapOverviewStack >( this );
69 mPainterJob->cancel();
94 QList<QgsLayoutItemMap *> mapsList;
95 mLayout->layoutItems( mapsList );
104 if ( map->mMapId == mMapId )
107 maxId = std::max( maxId, map->mMapId );
112 mLayout->itemsModel()->updateItemDisplayName(
this );
124 return tr(
"Map %1" ).arg( mMapId );
136 mCachedLayerStyleOverridesPresetName.clear();
140 updateAtlasFeature();
145 if ( rect().isEmpty() )
150 calculator.
setDpi( 25.4 );
157 double currentScaleDenominator =
scale();
164 double scaleRatio = scaleDenominator / currentScaleDenominator;
165 mExtent.
scale( scaleRatio );
167 if ( mAtlasDriven && mAtlasScalingMode ==
Fixed )
174 calculator.
setDpi( 25.4 );
175 scaleRatio = scaleDenominator / calculator.
calculate( mExtent, rect().width() );
176 mExtent.
scale( scaleRatio );
190 if ( mExtent == extent )
200 QRectF currentRect = rect();
202 double newHeight = currentRect.width() * mExtent.
height() / mExtent.
width();
214 double currentWidthHeightRatio = 1.0;
215 if ( !currentExtent.
isNull() )
216 currentWidthHeightRatio = currentExtent.
width() / currentExtent.
height();
218 currentWidthHeightRatio = rect().width() / rect().height();
219 double newWidthHeightRatio = newExtent.
width() / newExtent.
height();
221 if ( currentWidthHeightRatio < newWidthHeightRatio )
224 double newHeight = newExtent.
width() / currentWidthHeightRatio;
225 double deltaHeight = newHeight - newExtent.
height();
232 double newWidth = currentWidthHeightRatio * newExtent.
height();
233 double deltaWidth = newWidth - newExtent.
width();
238 if ( mExtent == newExtent )
260 mapPolygon( mExtent, poly );
269 return mLayout->project()->crs();
280 return _qgis_listRefToRaw( mLayers );
285 mLayers = _qgis_listRawToRef( layers );
290 if ( overrides == mLayerStyleOverrides )
293 mLayerStyleOverrides = overrides;
300 mLayerStyleOverrides.clear();
301 for (
const QgsMapLayerRef &layerRef : qgis::as_const( mLayers ) )
307 mLayerStyleOverrides.insert( layer->id(), style.
xmlData() );
314 mLastRenderedImageOffsetX -= dx;
315 mLastRenderedImageOffsetY -= dy;
318 transformShift( dx, dy );
342 double mapY = mExtent.
yMinimum() + ( 1 - ( point.y() / rect().height() ) ) * ( mExtent.
yMaximum() - mExtent.
yMinimum() );
348 centerX = mapX + ( centerX - mapX ) * ( 1.0 / factor );
349 centerY = mapY + ( centerY - mapY ) * ( 1.0 / factor );
351 double newIntervalX, newIntervalY;
368 if ( mAtlasDriven && mAtlasScalingMode ==
Fixed )
375 calculator.
setDpi( 25.4 );
376 double scaleRatio =
scale() / calculator.
calculate( mExtent, rect().width() );
377 mExtent.
scale( scaleRatio );
393 if ( layer->dataProvider() && layer->providerType() == QLatin1String(
"wms" ) )
429 if ( mOverviewStack->containsAdvancedEffects() )
435 if ( mGridStack->containsAdvancedEffects() )
447 mMapRotation = rotation;
448 mEvaluatedMapRotation = mMapRotation;
462 mAtlasDriven = enabled;
479 double margin = mAtlasMargin;
487 margin = ddMargin / 100;
499 if ( mGridStack->size() < 1 )
502 mGridStack->addGrid( grid );
504 return mGridStack->grid( 0 );
509 if ( mOverviewStack->size() < 1 )
512 mOverviewStack->addOverview( overview );
514 return mOverviewStack->overview( 0 );
525 mapElem.setAttribute( QStringLiteral(
"keepLayerSet" ), QStringLiteral(
"true" ) );
529 mapElem.setAttribute( QStringLiteral(
"keepLayerSet" ), QStringLiteral(
"false" ) );
532 if ( mDrawAnnotations )
534 mapElem.setAttribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"true" ) );
538 mapElem.setAttribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"false" ) );
542 QDomElement extentElem = doc.createElement( QStringLiteral(
"Extent" ) );
547 mapElem.appendChild( extentElem );
551 QDomElement crsElem = doc.createElement( QStringLiteral(
"crs" ) );
553 mapElem.appendChild( crsElem );
557 mapElem.setAttribute( QStringLiteral(
"followPreset" ), mFollowVisibilityPreset ? QStringLiteral(
"true" ) : QStringLiteral(
"false" ) );
558 mapElem.setAttribute( QStringLiteral(
"followPresetName" ), mFollowVisibilityPresetName );
561 mapElem.setAttribute( QStringLiteral(
"mapRotation" ), QString::number( mMapRotation ) );
564 QDomElement layerSetElem = doc.createElement( QStringLiteral(
"LayerSet" ) );
569 QDomElement layerElem = doc.createElement( QStringLiteral(
"Layer" ) );
570 QDomText layerIdText = doc.createTextNode( layerRef.layerId );
571 layerElem.appendChild( layerIdText );
573 layerElem.setAttribute( QStringLiteral(
"name" ), layerRef.name );
574 layerElem.setAttribute( QStringLiteral(
"source" ), layerRef.source );
575 layerElem.setAttribute( QStringLiteral(
"provider" ), layerRef.provider );
577 layerSetElem.appendChild( layerElem );
579 mapElem.appendChild( layerSetElem );
582 if ( mKeepLayerStyles )
584 QDomElement stylesElem = doc.createElement( QStringLiteral(
"LayerStyles" ) );
585 for (
auto styleIt = mLayerStyleOverrides.constBegin(); styleIt != mLayerStyleOverrides.constEnd(); ++styleIt )
587 QDomElement styleElem = doc.createElement( QStringLiteral(
"LayerStyle" ) );
592 styleElem.setAttribute( QStringLiteral(
"layerid" ), ref.layerId );
593 styleElem.setAttribute( QStringLiteral(
"name" ), ref.name );
594 styleElem.setAttribute( QStringLiteral(
"source" ), ref.source );
595 styleElem.setAttribute( QStringLiteral(
"provider" ), ref.provider );
599 stylesElem.appendChild( styleElem );
601 mapElem.appendChild( stylesElem );
605 mGridStack->writeXml( mapElem, doc, context );
608 mOverviewStack->writeXml( mapElem, doc, context );
611 QDomElement atlasElem = doc.createElement( QStringLiteral(
"AtlasMap" ) );
612 atlasElem.setAttribute( QStringLiteral(
"atlasDriven" ), mAtlasDriven );
613 atlasElem.setAttribute( QStringLiteral(
"scalingMode" ), mAtlasScalingMode );
614 atlasElem.setAttribute( QStringLiteral(
"margin" ),
qgsDoubleToString( mAtlasMargin ) );
615 mapElem.appendChild( atlasElem );
617 mapElem.setAttribute( QStringLiteral(
"labelMargin" ), mLabelMargin.
encodeMeasurement() );
618 mapElem.setAttribute( QStringLiteral(
"mapFlags" ), static_cast< int>( mMapFlags ) );
620 QDomElement labelBlockingItemsElem = doc.createElement( QStringLiteral(
"labelBlockingItems" ) );
621 for (
const auto &item : qgis::as_const( mBlockingLabelItems ) )
626 QDomElement blockingItemElem = doc.createElement( QStringLiteral(
"item" ) );
627 blockingItemElem.setAttribute( QStringLiteral(
"uuid" ), item->uuid() );
628 labelBlockingItemsElem.appendChild( blockingItemElem );
630 mapElem.appendChild( labelBlockingItemsElem );
637 mUpdatesEnabled =
false;
640 QDomNodeList extentNodeList = itemElem.elementsByTagName( QStringLiteral(
"Extent" ) );
641 if ( !extentNodeList.isEmpty() )
643 QDomElement extentElem = extentNodeList.at( 0 ).toElement();
644 double xmin, xmax, ymin, ymax;
645 xmin = extentElem.attribute( QStringLiteral(
"xmin" ) ).toDouble();
646 xmax = extentElem.attribute( QStringLiteral(
"xmax" ) ).toDouble();
647 ymin = extentElem.attribute( QStringLiteral(
"ymin" ) ).toDouble();
648 ymax = extentElem.attribute( QStringLiteral(
"ymax" ) ).toDouble();
652 QDomNodeList crsNodeList = itemElem.elementsByTagName( QStringLiteral(
"crs" ) );
653 if ( !crsNodeList.isEmpty() )
655 QDomElement crsElem = crsNodeList.at( 0 ).toElement();
664 mMapRotation = itemElem.attribute( QStringLiteral(
"mapRotation" ), QStringLiteral(
"0" ) ).toDouble();
665 mEvaluatedMapRotation = mMapRotation;
668 mFollowVisibilityPreset = itemElem.attribute( QStringLiteral(
"followPreset" ) ).compare( QLatin1String(
"true" ) ) == 0;
669 mFollowVisibilityPresetName = itemElem.attribute( QStringLiteral(
"followPresetName" ) );
672 QString keepLayerSetFlag = itemElem.attribute( QStringLiteral(
"keepLayerSet" ) );
673 if ( keepLayerSetFlag.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
675 mKeepLayerSet =
true;
679 mKeepLayerSet =
false;
682 QString drawCanvasItemsFlag = itemElem.attribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"true" ) );
683 if ( drawCanvasItemsFlag.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
685 mDrawAnnotations =
true;
689 mDrawAnnotations =
false;
692 mLayerStyleOverrides.clear();
696 QDomNodeList layerSetNodeList = itemElem.elementsByTagName( QStringLiteral(
"LayerSet" ) );
697 if ( !layerSetNodeList.isEmpty() )
699 QDomElement layerSetElem = layerSetNodeList.at( 0 ).toElement();
700 QDomNodeList layerIdNodeList = layerSetElem.elementsByTagName( QStringLiteral(
"Layer" ) );
701 mLayers.reserve( layerIdNodeList.size() );
702 for (
int i = 0; i < layerIdNodeList.size(); ++i )
704 QDomElement layerElem = layerIdNodeList.at( i ).toElement();
705 QString layerId = layerElem.text();
706 QString layerName = layerElem.attribute( QStringLiteral(
"name" ) );
707 QString layerSource = layerElem.attribute( QStringLiteral(
"source" ) );
708 QString layerProvider = layerElem.attribute( QStringLiteral(
"provider" ) );
710 QgsMapLayerRef ref( layerId, layerName, layerSource, layerProvider );
717 QDomNodeList layerStylesNodeList = itemElem.elementsByTagName( QStringLiteral(
"LayerStyles" ) );
718 mKeepLayerStyles = !layerStylesNodeList.isEmpty();
719 if ( mKeepLayerStyles )
721 QDomElement layerStylesElem = layerStylesNodeList.at( 0 ).toElement();
722 QDomNodeList layerStyleNodeList = layerStylesElem.elementsByTagName( QStringLiteral(
"LayerStyle" ) );
723 for (
int i = 0; i < layerStyleNodeList.size(); ++i )
725 const QDomElement &layerStyleElement = layerStyleNodeList.at( i ).toElement();
726 QString layerId = layerStyleElement.attribute( QStringLiteral(
"layerid" ) );
727 QString layerName = layerStyleElement.attribute( QStringLiteral(
"name" ) );
728 QString layerSource = layerStyleElement.attribute( QStringLiteral(
"source" ) );
729 QString layerProvider = layerStyleElement.attribute( QStringLiteral(
"provider" ) );
730 QgsMapLayerRef ref( layerId, layerName, layerSource, layerProvider );
734 style.
readXml( layerStyleElement );
740 mNumCachedLayers = 0;
741 mCacheInvalidated =
true;
744 mOverviewStack->readXml( itemElem, doc, context );
747 mGridStack->readXml( itemElem, doc, context );
750 QDomNodeList atlasNodeList = itemElem.elementsByTagName( QStringLiteral(
"AtlasMap" ) );
751 if ( !atlasNodeList.isEmpty() )
753 QDomElement atlasElem = atlasNodeList.at( 0 ).toElement();
754 mAtlasDriven = ( atlasElem.attribute( QStringLiteral(
"atlasDriven" ), QStringLiteral(
"0" ) ) != QLatin1String(
"0" ) );
755 if ( atlasElem.hasAttribute( QStringLiteral(
"fixedScale" ) ) )
757 mAtlasScalingMode = ( atlasElem.attribute( QStringLiteral(
"fixedScale" ), QStringLiteral(
"0" ) ) != QLatin1String(
"0" ) ) ?
Fixed :
Auto;
759 else if ( atlasElem.hasAttribute( QStringLiteral(
"scalingMode" ) ) )
761 mAtlasScalingMode =
static_cast<AtlasScalingMode>( atlasElem.attribute( QStringLiteral(
"scalingMode" ) ).toInt() );
763 mAtlasMargin = atlasElem.attribute( QStringLiteral(
"margin" ), QStringLiteral(
"0.1" ) ).toDouble();
768 mMapFlags =
static_cast< MapItemFlags
>( itemElem.attribute( QStringLiteral(
"mapFlags" ),
nullptr ).toInt() );
771 mBlockingLabelItems.clear();
772 mBlockingLabelItemUuids.clear();
773 QDomNodeList labelBlockingNodeList = itemElem.elementsByTagName( QStringLiteral(
"labelBlockingItems" ) );
774 if ( !labelBlockingNodeList.isEmpty() )
776 QDomElement blockingItems = labelBlockingNodeList.at( 0 ).toElement();
777 QDomNodeList labelBlockingNodeList = blockingItems.childNodes();
778 for (
int i = 0; i < labelBlockingNodeList.size(); ++i )
780 const QDomElement &itemBlockingElement = labelBlockingNodeList.at( i ).toElement();
781 const QString itemUuid = itemBlockingElement.attribute( QStringLiteral(
"uuid" ) );
782 mBlockingLabelItemUuids << itemUuid;
788 mUpdatesEnabled =
true;
794 if ( !
mLayout || !painter || !painter->device() || !mUpdatesEnabled )
803 QRectF thisPaintRect = rect();
809 if (
mLayout->renderContext().isPreviewRender() )
812 painter->setClipRect( thisPaintRect );
813 if ( !mCacheFinalImage || mCacheFinalImage->isNull() )
816 painter->setBrush( QBrush( QColor( 125, 125, 125, 125 ) ) );
817 painter->drawRect( thisPaintRect );
818 painter->setBrush( Qt::NoBrush );
820 messageFont.setPointSize( 12 );
821 painter->setFont( messageFont );
822 painter->setPen( QColor( 255, 255, 255, 255 ) );
823 painter->drawText( thisPaintRect, Qt::AlignCenter | Qt::AlignHCenter, tr(
"Rendering map" ) );
824 if ( mPainterJob && mCacheInvalidated && !mDrawingPreview )
828 mBackgroundUpdateTimer->start( 1 );
830 else if ( !mPainterJob && !mDrawingPreview )
834 mBackgroundUpdateTimer->start( 1 );
839 if ( mCacheInvalidated && !mDrawingPreview )
843 mBackgroundUpdateTimer->start( 1 );
848 double imagePixelWidth = mCacheFinalImage->width();
849 double scale = rect().width() / imagePixelWidth;
853 painter->translate( mLastRenderedImageOffsetX + mXOffset, mLastRenderedImageOffsetY + mYOffset );
854 painter->scale( scale, scale );
855 painter->drawImage( 0, 0, *mCacheFinalImage );
861 painter->setClipRect( thisPaintRect, Qt::NoClip );
863 mOverviewStack->drawItems( painter,
false );
864 mGridStack->drawItems( painter );
866 drawMapFrame( painter );
875 QPaintDevice *paintDevice = painter->device();
887 int widthInPixels =
static_cast< int >( std::round(
boundingRect().width() * layoutUnitsInInches * destinationDpi ) );
888 int heightInPixels =
static_cast< int >( std::round(
boundingRect().height() * layoutUnitsInInches * destinationDpi ) );
889 QImage image = QImage( widthInPixels, heightInPixels, QImage::Format_ARGB32 );
891 image.fill( Qt::transparent );
892 image.setDotsPerMeterX( static_cast< int >( std::round( 1000 * destinationDpi / 25.4 ) ) );
893 image.setDotsPerMeterY( static_cast< int >( std::round( 1000 * destinationDpi / 25.4 ) ) );
894 double dotsPerMM = destinationDpi / 25.4;
895 QPainter p( &image );
898 QRect imagePaintRect( static_cast< int >( std::round( tl.x() * dotsPerMM ) ),
899 static_cast< int >( std::round( tl.y() * dotsPerMM ) ),
900 static_cast< int >( std::round( thisPaintRect.width() * dotsPerMM ) ),
901 static_cast< int >( std::round( thisPaintRect.height() * dotsPerMM ) ) );
902 p.setClipRect( imagePaintRect );
904 p.translate( imagePaintRect.topLeft() );
908 if ( shouldDrawPart( Background ) )
910 p.scale( dotsPerMM, dotsPerMM );
911 drawMapBackground( &p );
912 p.scale( 1.0 / dotsPerMM, 1.0 / dotsPerMM );
915 drawMap( &p, cExtent, imagePaintRect.size(), image.logicalDpiX() );
920 p.scale( dotsPerMM, dotsPerMM );
922 if ( shouldDrawPart( OverviewMapExtent ) )
924 mOverviewStack->drawItems( &p,
false );
926 if ( shouldDrawPart( Grid ) )
928 mGridStack->drawItems( &p );
933 painter->scale( 1 / dotsPerMM, 1 / dotsPerMM );
934 painter->drawImage( QPointF( -tl.x()* dotsPerMM, -tl.y() * dotsPerMM ), image );
935 painter->scale( dotsPerMM, dotsPerMM );
941 if ( shouldDrawPart( Background ) )
943 drawMapBackground( painter );
947 painter->setClipRect( thisPaintRect );
952 painter->translate( mXOffset, mYOffset );
954 double dotsPerMM = paintDevice->logicalDpiX() / 25.4;
956 painter->scale( 1 / dotsPerMM, 1 / dotsPerMM );
958 if ( mCurrentExportPart != NotLayered )
960 if ( !mStagedRendererJob )
962 createStagedRenderJob( cExtent, size, paintDevice->logicalDpiX() );
965 mStagedRendererJob->renderCurrentPart( painter );
969 drawMap( painter, cExtent, size, paintDevice->logicalDpiX() );
975 painter->setClipRect( thisPaintRect, Qt::NoClip );
977 if ( shouldDrawPart( OverviewMapExtent ) )
979 mOverviewStack->drawItems( painter,
false );
981 if ( shouldDrawPart( Grid ) )
983 mGridStack->drawItems( painter );
989 if ( shouldDrawPart( Frame ) )
991 drawMapFrame( painter );
1002 + ( layerCount + ( layerCount ? 1 : 0 ) )
1003 + ( mGridStack->hasEnabledItems() ? 1 : 0 )
1004 + ( mOverviewStack->hasEnabledItems() ? 1 : 0 )
1010 mCurrentExportPart = Start;
1012 mExportThemes = !mFollowVisibilityPreset ?
mLayout->renderContext().exportThemes() : QStringList();
1013 mExportThemeIt = mExportThemes.begin();
1018 mCurrentExportPart = NotLayered;
1019 mExportThemes.clear();
1020 mExportThemeIt = mExportThemes.begin();
1025 switch ( mCurrentExportPart )
1030 mCurrentExportPart = Background;
1036 mCurrentExportPart = Layer;
1040 if ( mStagedRendererJob )
1042 if ( mStagedRendererJob->nextPart() )
1045 mStagedRendererJob.reset();
1048 if ( mExportThemeIt != mExportThemes.end() && ++mExportThemeIt != mExportThemes.end() )
1054 if ( mGridStack->hasEnabledItems() )
1056 mCurrentExportPart = Grid;
1062 for (
int i = 0; i < mOverviewStack->size(); ++i )
1067 mCurrentExportPart = OverviewMapExtent;
1073 case OverviewMapExtent:
1076 mCurrentExportPart = Frame;
1083 if ( isSelected() && !
mLayout->renderContext().isPreviewRender() )
1085 mCurrentExportPart = SelectionBoxes;
1090 case SelectionBoxes:
1091 mCurrentExportPart = End;
1112 switch ( mCurrentExportPart )
1122 if ( !mExportThemes.empty() && mExportThemeIt != mExportThemes.end() )
1125 if ( mStagedRendererJob )
1127 switch ( mStagedRendererJob->currentStage() )
1131 detail.
mapLayerId = mStagedRendererJob->currentLayerId();
1137 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), layer->name() );
1142 const QList<QgsLayoutItemMapOverview *> res = mOverviewStack->asList();
1148 if ( item->mapLayer() && detail.
mapLayerId == item->mapLayer()->id() )
1151 detail.
name = QStringLiteral(
"%1 (%2): %3" ).arg(
displayName(), detail.
mapTheme, item->mapLayer()->name() );
1153 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), item->mapLayer()->name() );
1162 detail.
mapLayerId = mStagedRendererJob->currentLayerId();
1168 detail.
name = tr(
"%1: %2 (Labels)" ).arg(
displayName(), layer->name() );
1187 if ( !layers.isEmpty() )
1203 case OverviewMapExtent:
1211 case SelectionBoxes:
1226 void QgsLayoutItemMap::drawMap( QPainter *painter,
const QgsRectangle &
extent, QSizeF size,
double dpi )
1240 if ( shouldDrawPart( OverviewMapExtent ) )
1251 mRenderingErrors = job.
errors();
1254 void QgsLayoutItemMap::recreateCachedImageInBackground()
1260 QPainter *oldPainter = mPainter.release();
1261 QImage *oldImage = mCacheRenderingImage.release();
1264 oldJob->deleteLater();
1268 oldJob->cancelWithoutBlocking();
1272 mCacheRenderingImage.reset(
nullptr );
1276 Q_ASSERT( !mPainterJob );
1277 Q_ASSERT( !mPainter );
1278 Q_ASSERT( !mCacheRenderingImage );
1284 int w =
static_cast< int >( std::round( widthLayoutUnits * mPreviewScaleFactor ) );
1285 int h =
static_cast< int >( std::round( heightLayoutUnits * mPreviewScaleFactor ) );
1288 if ( w > 5000 || h > 5000 )
1293 h =
static_cast< int>( std::round( w * heightLayoutUnits / widthLayoutUnits ) );
1298 w =
static_cast< int >( std::round( h * widthLayoutUnits / heightLayoutUnits ) );
1302 if ( w <= 0 || h <= 0 )
1305 mCacheRenderingImage.reset(
new QImage( w, h, QImage::Format_ARGB32 ) );
1308 mCacheRenderingImage->setDotsPerMeterX( static_cast< int >( std::round( 1000 * w / widthLayoutUnits ) ) );
1309 mCacheRenderingImage->setDotsPerMeterY( static_cast< int >( std::round( 1000 * h / heightLayoutUnits ) ) );
1320 mCacheRenderingImage->fill( QColor( 255, 255, 255, 0 ).rgba() );
1323 mCacheInvalidated =
false;
1324 mPainter.reset(
new QPainter( mCacheRenderingImage.get() ) );
1327 if ( shouldDrawPart( OverviewMapExtent ) )
1329 settings.
setLayers( mOverviewStack->modifyMapLayerList( settings.
layers() ) );
1334 mPainterJob->start();
1346 mDrawingPreview =
false;
1370 jobMapSettings.
setRotation( mEvaluatedMapRotation );
1374 if ( includeLayerSettings )
1382 if ( !
mLayout->renderContext().isPreviewRender() )
1417 if ( mEvaluatedLabelMargin.
length() > 0 )
1420 visiblePoly.append( visiblePoly.at( 0 ) );
1421 const double layoutLabelMargin =
mLayout->convertToLayoutUnits( mEvaluatedLabelMargin );
1422 const double layoutLabelMarginInMapUnits = layoutLabelMargin / rect().width() * jobMapSettings.
extent().
width();
1424 mapBoundaryGeom = mapBoundaryGeom.
buffer( -layoutLabelMarginInMapUnits, 0 );
1428 if ( !mBlockingLabelItems.isEmpty() )
1438 return jobMapSettings;
1445 mBlockingLabelItems.clear();
1446 for (
const QString &
uuid : qgis::as_const( mBlockingLabelItemUuids ) )
1455 mOverviewStack->finalizeRestoreFromXml();
1456 mGridStack->finalizeRestoreFromXml();
1467 return mCurrentRectangle;
1500 QVariantList layersIds;
1510 const QList<QgsMapLayer *> layersInMap =
layersToRender( &context );
1512 layersIds.reserve( layersInMap.count() );
1513 layers.reserve( layersInMap.count() );
1516 layersIds << layer->id();
1522 scope->
addFunction( QStringLiteral(
"is_layer_visible" ),
new QgsExpressionContextUtils::GetLayerVisibility( layersInMap,
scale() ) );
1530 if ( extentWidth <= 0 )
1534 return rect().width() / extentWidth;
1539 double dx = mXOffset;
1540 double dy = mYOffset;
1541 transformShift( dx, dy );
1543 poly.translate( -dx, -dy );
1549 if ( !mBlockingLabelItems.contains( item ) )
1550 mBlockingLabelItems.append( item );
1557 mBlockingLabelItems.removeAll( item );
1564 return mBlockingLabelItems.contains( item );
1573 if ( mOverviewStack )
1575 for (
int i = 0; i < mOverviewStack->size(); ++i )
1577 if ( mOverviewStack->item( i )->accept( visitor ) )
1584 for (
int i = 0; i < mGridStack->size(); ++i )
1586 if ( mGridStack->item( i )->accept( visitor ) )
1599 mRenderedFeatureHandlers.append( handler );
1604 mRenderedFeatureHandlers.removeAll( handler );
1610 if ( mapPoly.empty() )
1612 return QPointF( 0, 0 );
1617 double dx = mapCoords.x() - rotationPoint.
x();
1618 double dy = mapCoords.y() - rotationPoint.
y();
1620 QgsPointXY backRotatedCoords( rotationPoint.
x() + dx, rotationPoint.
y() + dy );
1623 double xItem = rect().width() * ( backRotatedCoords.x() - unrotatedExtent.xMinimum() ) / unrotatedExtent.width();
1624 double yItem = rect().height() * ( 1 - ( backRotatedCoords.y() - unrotatedExtent.yMinimum() ) / unrotatedExtent.height() );
1625 return QPointF( xItem, yItem );
1639 mapPolygon( newExtent, poly );
1640 QRectF bRect = poly.boundingRect();
1654 mCacheInvalidated =
true;
1660 QRectF rectangle = rect();
1661 double frameExtension =
frameEnabled() ? pen().widthF() / 2.0 : 0.0;
1663 double topExtension = 0.0;
1664 double rightExtension = 0.0;
1665 double bottomExtension = 0.0;
1666 double leftExtension = 0.0;
1669 mGridStack->calculateMaxGridExtension( topExtension, rightExtension, bottomExtension, leftExtension );
1671 topExtension = std::max( topExtension, frameExtension );
1672 rightExtension = std::max( rightExtension, frameExtension );
1673 bottomExtension = std::max( bottomExtension, frameExtension );
1674 leftExtension = std::max( leftExtension, frameExtension );
1676 rectangle.setLeft( rectangle.left() - leftExtension );
1677 rectangle.setRight( rectangle.right() + rightExtension );
1678 rectangle.setTop( rectangle.top() - topExtension );
1679 rectangle.setBottom( rectangle.bottom() + bottomExtension );
1680 if ( rectangle != mCurrentRectangle )
1682 prepareGeometryChange();
1683 mCurrentRectangle = rectangle;
1699 refreshMapExtents( &context );
1701 if ( mExtent != beforeExtent )
1708 refreshLabelMargin(
false );
1712 mCacheInvalidated =
true;
1717 void QgsLayoutItemMap::layersAboutToBeRemoved(
const QList<QgsMapLayer *> &
layers )
1719 if ( !mLayers.isEmpty() || mLayerStyleOverrides.isEmpty() )
1723 mLayerStyleOverrides.remove( layer->id() );
1725 _qgis_removeLayers( mLayers, layers );
1729 void QgsLayoutItemMap::painterJobFinished()
1732 mPainterJob.reset(
nullptr );
1733 mPainter.reset(
nullptr );
1734 mCacheFinalImage = std::move( mCacheRenderingImage );
1735 mLastRenderedImageOffsetX = 0;
1736 mLastRenderedImageOffsetY = 0;
1741 void QgsLayoutItemMap::shapeChanged()
1746 double w = rect().width();
1747 double h = rect().height();
1750 double newWidth = mExtent.
width();
1752 double newHeight = newWidth * h / w;
1757 refreshMapExtents();
1764 void QgsLayoutItemMap::mapThemeChanged(
const QString &theme )
1766 if ( theme == mCachedLayerStyleOverridesPresetName )
1767 mCachedLayerStyleOverridesPresetName.clear();
1770 void QgsLayoutItemMap::connectUpdateSlot()
1778 this, &QgsLayoutItemMap::layersAboutToBeRemoved );
1782 if (
layers().isEmpty() )
1808 updateAtlasFeature();
1817 QTransform mapTransform;
1818 QPolygonF thisRectPoly = QPolygonF( QRectF( 0, 0, rect().width(), rect().height() ) );
1820 thisRectPoly.pop_back();
1821 thisExtent.pop_back();
1823 QPolygonF thisItemPolyInLayout = mapToScene( thisRectPoly );
1826 QTransform::quadToQuad( thisItemPolyInLayout, thisExtent, mapTransform );
1827 return mapTransform;
1830 QList<QgsLabelBlockingRegion> QgsLayoutItemMap::createLabelBlockingRegions(
const QgsMapSettings & )
const 1833 QList< QgsLabelBlockingRegion > blockers;
1834 blockers.reserve( mBlockingLabelItems.count() );
1835 for (
const auto &item : qgis::as_const( mBlockingLabelItems ) )
1842 if ( item->property(
"wasVisible" ).isValid() )
1844 if ( !item->property(
"wasVisible" ).toBool() )
1847 else if ( !item->isVisible() )
1850 QPolygonF itemRectInMapCoordinates = mapTransform.map( item->mapToScene( item->rect() ) );
1851 itemRectInMapCoordinates.append( itemRectInMapCoordinates.at( 0 ) );
1860 return mLabelMargin;
1865 mLabelMargin = margin;
1866 refreshLabelMargin(
false );
1869 void QgsLayoutItemMap::updateToolTip()
1878 if ( mFollowVisibilityPreset )
1880 presetName = mFollowVisibilityPresetName;
1884 else if ( !mExportThemes.empty() && mExportThemeIt != mExportThemes.end() )
1885 presetName = *mExportThemeIt;
1896 QList<QgsMapLayer *> renderLayers;
1898 QString presetName = themeToRender( *evalContext );
1899 if ( !presetName.isEmpty() )
1901 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
1902 renderLayers =
mLayout->project()->mapThemeCollection()->mapThemeVisibleLayers( presetName );
1904 renderLayers =
mLayout->project()->mapThemeCollection()->masterVisibleLayers();
1906 else if ( !
layers().isEmpty() )
1912 renderLayers =
mLayout->project()->mapThemeCollection()->masterVisibleLayers();
1919 renderLayers.clear();
1921 const QStringList layerNames = ddLayers.split(
'|' );
1923 for (
const QString &name : layerNames )
1925 const QList< QgsMapLayer * > matchingLayers =
mLayout->project()->mapLayersByName( name );
1928 renderLayers << layer;
1937 int removeAt = renderLayers.indexOf(
mLayout->reportContext().layer() );
1938 if ( removeAt != -1 )
1940 renderLayers.removeAt( removeAt );
1945 renderLayers.erase( std::remove_if( renderLayers.begin(), renderLayers.end(), [](
QgsMapLayer * layer )
1947 return !layer || !layer->isValid();
1948 } ), renderLayers.end() );
1950 return renderLayers;
1953 QMap<QString, QString> QgsLayoutItemMap::layerStyleOverridesToRender(
const QgsExpressionContext &context )
const 1955 QString presetName = themeToRender( context );
1956 if ( !presetName.isEmpty() )
1958 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
1960 if ( presetName != mCachedLayerStyleOverridesPresetName )
1963 mCachedPresetLayerStyleOverrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( presetName );
1964 mCachedLayerStyleOverridesPresetName = presetName;
1967 return mCachedPresetLayerStyleOverrides;
1970 return QMap<QString, QString>();
1972 else if ( mFollowVisibilityPreset )
1974 QString presetName = mFollowVisibilityPresetName;
1977 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
1979 if ( presetName.isEmpty() || presetName != mCachedLayerStyleOverridesPresetName )
1982 mCachedPresetLayerStyleOverrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( presetName );
1983 mCachedLayerStyleOverridesPresetName = presetName;
1986 return mCachedPresetLayerStyleOverrides;
1989 return QMap<QString, QString>();
1991 else if ( mKeepLayerStyles )
1993 return mLayerStyleOverrides;
1997 return QMap<QString, QString>();
2001 QgsRectangle QgsLayoutItemMap::transformedExtent()
const 2003 double dx = mXOffset;
2004 double dy = mYOffset;
2005 transformShift( dx, dy );
2009 void QgsLayoutItemMap::mapPolygon(
const QgsRectangle &extent, QPolygonF &poly )
const 2019 poly << QPointF( poly.at( 0 ) );
2028 dx = rotationPoint.
x() - extent.
xMinimum();
2029 dy = rotationPoint.
y() - extent.
yMaximum();
2031 poly << QPointF( rotationPoint.
x() - dx, rotationPoint.
y() - dy );
2034 dx = rotationPoint.
x() - extent.
xMaximum();
2035 dy = rotationPoint.
y() - extent.
yMaximum();
2037 poly << QPointF( rotationPoint.
x() - dx, rotationPoint.
y() - dy );
2040 dx = rotationPoint.
x() - extent.
xMaximum();
2041 dy = rotationPoint.
y() - extent.
yMinimum();
2043 poly << QPointF( rotationPoint.
x() - dx, rotationPoint.
y() - dy );
2046 dx = rotationPoint.
x() - extent.
xMinimum();
2047 dy = rotationPoint.
y() - extent.
yMinimum();
2049 poly << QPointF( rotationPoint.
x() - dx, rotationPoint.
y() - dy );
2052 poly << QPointF( poly.at( 0 ) );
2055 void QgsLayoutItemMap::transformShift(
double &xShift,
double &yShift )
const 2058 double dxScaled = xShift * mmToMapUnits;
2059 double dyScaled = - yShift * mmToMapUnits;
2074 const QList< QgsAnnotation * > annotations =
mLayout->project()->annotationManager()->annotations();
2075 if ( annotations.isEmpty() )
2085 if ( !annotation || !annotation->isVisible() )
2089 if ( annotation->mapLayer() && !layers.contains( annotation->mapLayer() ) )
2092 drawAnnotation( annotation, rc );
2106 double itemX, itemY;
2109 QPointF mapPos = layoutMapPosForItem( annotation );
2118 context.
painter()->translate( itemX, itemY );
2121 double dotsPerMM = context.
painter()->device()->logicalDpiX() / 25.4;
2122 context.
painter()->scale( 1 / dotsPerMM, 1 / dotsPerMM );
2124 annotation->
render( context );
2128 QPointF QgsLayoutItemMap::layoutMapPosForItem(
const QgsAnnotation *annotation )
const 2131 return QPointF( 0, 0 );
2140 if ( annotationCrs !=
crs() )
2157 void QgsLayoutItemMap::drawMapFrame( QPainter *p )
2163 p->setBrush( Qt::NoBrush );
2164 p->setRenderHint( QPainter::Antialiasing,
true );
2165 p->drawRect( QRectF( 0, 0, rect().width(), rect().height() ) );
2170 void QgsLayoutItemMap::drawMapBackground( QPainter *p )
2175 p->setBrush( brush() );
2176 p->setPen( Qt::NoPen );
2177 p->setRenderHint( QPainter::Antialiasing,
true );
2178 p->drawRect( QRectF( 0, 0, rect().width(), rect().height() ) );
2183 bool QgsLayoutItemMap::shouldDrawPart( QgsLayoutItemMap::PartType part )
const 2185 if ( mCurrentExportPart == NotLayered )
2203 return mCurrentExportPart == Layer;
2206 return mCurrentExportPart == Grid && mGridStack->hasEnabledItems();
2208 case OverviewMapExtent:
2209 return mCurrentExportPart == OverviewMapExtent && mOverviewStack->hasEnabledItems();
2214 case SelectionBoxes:
2215 return mCurrentExportPart == SelectionBoxes && isSelected();
2233 bool useDdXMin =
false;
2234 bool useDdXMax =
false;
2235 bool useDdYMin =
false;
2236 bool useDdYMax =
false;
2268 if ( newExtent != mExtent )
2274 double currentWidthHeightRatio = mExtent.
width() / mExtent.
height();
2275 double newWidthHeightRatio = newExtent.
width() / newExtent.
height();
2277 if ( currentWidthHeightRatio < newWidthHeightRatio )
2280 double newHeight = newExtent.
width() / currentWidthHeightRatio;
2281 double deltaHeight = newHeight - newExtent.
height();
2288 double newWidth = currentWidthHeightRatio * newExtent.
height();
2289 double deltaWidth = newWidth - newExtent.
width();
2294 mExtent = newExtent;
2304 newExtent = mExtent;
2307 if ( useDdXMax || useDdXMin || useDdYMax || useDdYMin )
2311 if ( useDdXMin && !useDdXMax )
2317 else if ( !useDdXMin && useDdXMax )
2323 if ( useDdYMin && !useDdYMax )
2329 else if ( !useDdYMin && useDdYMax )
2336 if ( newExtent != mExtent )
2338 mExtent = newExtent;
2355 void QgsLayoutItemMap::refreshLabelMargin(
bool updateItem )
2359 mEvaluatedLabelMargin.
setLength( labelMargin );
2368 void QgsLayoutItemMap::updateAtlasFeature()
2387 if ( mAtlasScalingMode ==
Fixed || mAtlasScalingMode ==
Predefined || isPointLayer )
2392 double originalScale = calc.
calculate( originalExtent, rect().width() );
2393 double geomCenterX = ( xa1 + xa2 ) / 2.0;
2394 double geomCenterY = ( ya1 + ya2 ) / 2.0;
2395 QVector<qreal> scales;
2397 if ( !
mLayout->reportContext().predefinedScales().empty() )
2398 scales =
mLayout->reportContext().predefinedScales();
2400 scales =
mLayout->renderContext().predefinedScales();
2402 if ( mAtlasScalingMode ==
Fixed || isPointLayer || scales.isEmpty() )
2405 double xMin = geomCenterX - originalExtent.
width() / 2.0;
2406 double yMin = geomCenterY - originalExtent.
height() / 2.0;
2409 xMin + originalExtent.
width(),
2410 yMin + originalExtent.
height() );
2414 double newScale = calc.
calculate( newExtent, rect().width() );
2415 newExtent.
scale( originalScale / newScale );
2420 double newWidth = originalExtent.
width();
2421 double newHeight = originalExtent.
height();
2422 for (
int i = 0; i < scales.size(); i++ )
2424 double ratio = scales[i] / originalScale;
2425 newWidth = originalExtent.
width() * ratio;
2426 newHeight = originalExtent.
height() * ratio;
2429 double xMin = geomCenterX - newWidth / 2.0;
2430 double yMin = geomCenterY - newHeight / 2.0;
2438 double newScale = calc.
calculate( newExtent, rect().width() );
2439 newExtent.
scale( scales[i] / newScale );
2449 else if ( mAtlasScalingMode ==
Auto )
2453 double geomRatio = bounds.
width() / bounds.
height();
2454 double mapRatio = originalExtent.
width() / originalExtent.
height();
2457 if ( geomRatio < mapRatio )
2460 double adjWidth = ( mapRatio * bounds.
height() - bounds.
width() ) / 2.0;
2465 else if ( geomRatio > mapRatio )
2468 double adjHeight = ( bounds.
width() / mapRatio - bounds.
height() ) / 2.0;
2474 const double evaluatedAtlasMargin =
atlasMargin();
2475 if ( evaluatedAtlasMargin > 0.0 )
2477 newExtent.
scale( 1 + evaluatedAtlasMargin );
2493 if ( mEvaluatedMapRotation != 0.0 )
2503 double dx = std::max( std::abs( prevCenter.
x() - bounds.
xMinimum() ),
2504 std::abs( prevCenter.
x() - bounds.
xMaximum() ) );
2505 double dy = std::max( std::abs( prevCenter.
y() - bounds.
yMinimum() ),
2506 std::abs( prevCenter.
y() - bounds.
yMaximum() ) );
2509 center.
x() + dx, center.
y() + dy );
2517 void QgsLayoutItemMap::createStagedRenderJob(
const QgsRectangle &extent,
const QSizeF size,
double dpi )
2520 settings.
setLayers( mOverviewStack->modifyMapLayerList( settings.
layers() ) );
2522 mStagedRendererJob = qgis::make_unique< QgsMapRendererStagedRenderJob >( settings,
2525 : QgsMapRendererStagedRenderJob::Flags(
nullptr ) );
2526 mStagedRendererJob->start();
QIcon icon() const override
Returns the item's icon.
QString displayName() const override
Gets item display name.
void setForceVectorOutput(bool force)
Sets whether rendering operations should use vector operations instead of any faster raster shortcuts...
The class is used as a container of context for various read/write operations on other objects...
QgsUnitTypes::LayoutUnit units() const
Returns the units for the measurement.
static double scaleFactorFromItemStyle(const QStyleOptionGraphicsItem *style)
Extracts the scale factor from an item style.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
void draw(QgsLayoutItemRenderContext &context) override
Draws the item's contents using the specified item render context.
void finished()
emitted when asynchronous rendering is finished (or canceled).
Single variable definition for use within a QgsExpressionContextScope.
void addLabelBlockingItem(QgsLayoutItem *item)
Sets the specified layout item as a "label blocking item" for this map.
QTransform layoutToMapCoordsTransform() const
Creates a transform from layout coordinates to map coordinates.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
sets destination coordinate reference system
A rectangle specified with double values.
Base class for all map layer types.
void setExtent(const QgsRectangle &rect, bool magnified=true)
Set coordinates of the rectangle which should be rendered.
Job implementation that renders everything sequentially using a custom painter.
bool isVisible() const
Returns true if the annotation is visible and should be rendered.
QPointF mapToItemCoords(QPointF mapCoords) const
Transforms map coordinates to item coordinates (considering rotation and move offset) ...
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the coordinate transform context, which stores various information regarding which datum transfo...
bool containsAdvancedEffects() const override
Returns true if the item contains contents with blend modes or transparency effects which can only be...
Base class for graphical items within a QgsLayout.
An individual overview which is drawn above the map content in a QgsLayoutItemMap, and shows the extent of another QgsLayoutItemMap.
virtual bool containsAdvancedEffects() const
Returns true if the item contains contents with blend modes or transparency effects which can only be...
static Q_INVOKABLE QString toString(QgsUnitTypes::DistanceUnit unit)
Returns a translated string representing a distance unit.
QgsLayoutItemMap(QgsLayout *layout)
Constructor for QgsLayoutItemMap, with the specified parent layout.
void moveContent(double dx, double dy) override
Moves the content of the item, by a specified dx and dy in layout units.
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...
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
void setXMaximum(double x)
Set the maximum x value.
int type() const override
Use antialiasing while drawing.
QString xmlData() const
Returns XML content of the style.
void startLayeredExport() override
Starts a multi-layer export operation.
void removeRenderedFeatureHandler(QgsRenderedFeatureHandlerInterface *handler)
Removes a previously added rendered feature handler.
Item contains multiple sublayers which must be individually exported.
QString toProj() const
Returns a Proj string representation of this CRS.
void readXml(const QDomElement &styleElement)
Read style configuration (for project file reading)
void addFunction(const QString &name, QgsScopedExpressionFunction *function)
Adds a function to the scope.
Layer and style map theme.
bool writePropertiesToElement(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const override
Stores item state within an XML DOM element.
TYPE * resolveWeakly(const QgsProject *project, MatchType matchType=MatchType::All)
Resolves the map layer by attempting to find a matching layer in a project using a weak match...
void setExtent(const QgsRectangle &extent)
Sets a new extent for the map.
void layerOrderChanged()
Emitted when the layer order has changed.
An item which is drawn inside a QgsLayoutItemMap, e.g., a grid or map overview.
A class to represent a 2D point.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
QgsMapSettings mapSettings(const QgsRectangle &extent, QSizeF size, double dpi, bool includeLayerSettings) const
Returns map settings that will be used for drawing of the map.
void extentChanged()
Emitted when the map's extent changes.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
OperationResult rotate(double rotation, const QgsPointXY ¢er)
Rotate this geometry around the Z axis.
static QgsLayoutItemMap * create(QgsLayout *layout)
Returns a new map item for the specified layout.
Whether to use also label candidates that are partially outside of the map view.
bool frameEnabled() const
Returns true if the item includes a frame.
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
void setOutputDpi(double dpi)
Sets DPI used for conversion between real world units (e.g. mm) and pixels.
#define Q_NOWARN_DEPRECATED_PUSH
void crsChanged()
Emitted when the CRS of the project has changed.
void setDpi(double dpi)
Sets the dpi (dots per inch) for the output resolution, to be used in scale calculations.
Errors errors() const
List of errors that happened during the rendering job - available when the rendering has been finishe...
void zoomContent(double factor, QPointF point) override
Zooms content of item.
A geometry is the spatial representation of a feature.
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
virtual void setFrameStrokeWidth(QgsLayoutMeasurement width)
Sets the frame stroke width.
static const QStringList containsAdvancedEffects(const QgsMapSettings &mapSettings)
Checks whether any of the layers attached to a map settings object contain advanced effects...
QgsGeometry buffer(double distance, int segments) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
bool drawAnnotations() const
Returns whether annotations are drawn within the map.
Flags flags() const
Returns combination of flags used for rendering.
QgsUnitTypes::DistanceUnit mapUnits
void invalidateCache() override
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Set map of map layer style overrides (key: layer ID, value: style name) where a different style shoul...
void preparedForAtlas()
Emitted when the map has been prepared for atlas rendering, just before actual rendering.
QString mapTheme
Associated map theme, or an empty string if this export layer does not need to be associated with a m...
QList< QgsMapLayer * > layers() const
Gets list of layers for map rendering The layers are stored in the reverse order of how they are rend...
An interface for classes which can visit style entity (e.g.
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
Enable layer opacity and blending effects.
Individual item in a print layout.
QPolygonF transformedMapPolygon() const
Returns extent that considers rotation and shift with mOffsetX / mOffsetY.
friend class QgsLayoutItemMapOverview
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
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...
QgsLayoutItem::ExportLayerDetail exportLayerDetails() const override
Returns the details for the specified current export layer.
QPointF relativePosition() const
Returns the relative position of the annotation, if it is not attached to a fixed map position...
Vector graphics should not be cached and drawn as raster images.
void setFlag(Flag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected)
Abstract base class for annotation items which are drawn over a map.
void setFrameStrokeWidth(QgsLayoutMeasurement width) override
Sets the frame stroke width.
The QgsMapSettings class contains configuration for rendering of the map.
PropertyValueType
Specifies whether the value returned by a function should be the original, user set value...
void readFromLayer(QgsMapLayer *layer)
Store layer's active style information in the instance.
void storeCurrentLayerStyles()
Stores the current project layer styles into style overrides.
void sizePositionChanged()
Emitted when the item's size or position changes.
Stores style information (renderer, opacity, labeling, diagrams etc.) applicable to a map layer...
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
QString name
User-friendly name for the export layer.
No simplification can be applied.
void mapThemeChanged(const QString &theme)
Emitted when a map theme changes definition.
static QgsRectangle fromCenterAndSize(QgsPointXY center, double width, double height)
Creates a new rectangle, given the specified center point and width and height.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
QString ellipsoidAcronym() const
Returns the ellipsoid acronym for the ellipsoid used by the CRS.
QList< QgsMapLayer * > layers() const
Returns the stored layer set.
QgsRectangle extent() const
Returns the current map extent.
Layout graphical items for displaying a map.
void setOutputSize(QSize size)
Sets the size of the resulting map image.
QString layerId
Original layer ID.
void backgroundTaskCountChanged(int count)
Emitted whenever the number of background tasks an item is executing changes.
QgsPropertyCollection mDataDefinedProperties
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
const QgsLayout * layout() const
Returns the layout the object is attached to.
Whether to render unplaced labels as an indicator/warning for users.
void setTextRenderFormat(QgsRenderContext::TextRenderFormat format)
Sets the text render format, which dictates how text is rendered (e.g.
QgsMapThemeCollection mapThemeCollection
void setLength(const double length)
Sets the length of the measurement.
void setLayers(const QList< QgsMapLayer *> &layers)
Sets the stored layers set.
This class provides a method of storing measurements for use in QGIS layouts using a variety of diffe...
bool requiresRasterization() const override
Returns true if the item is drawn in such a way that forces the whole layout to be rasterized when ex...
bool hasBackground() const
Returns true if the item has a background.
virtual bool visitExit(const QgsStyleEntityVisitorInterface::Node &node)
Called when the visitor stops visiting a node.
Whether vector selections should be shown in the rendered map.
double width() const
Returns the width of the rectangle.
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
~QgsLayoutItemMap() override
void setYMinimum(double y)
Set the minimum y value.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
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...
double atlasMargin(QgsLayoutObject::PropertyValueType valueType=QgsLayoutObject::EvaluatedValue)
Returns the margin size (percentage) used when the map is in atlas mode.
static QgsRenderContext createRenderContextForMap(QgsLayoutItemMap *map, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout map and painter destination.
QColor backgroundColor() const
Returns the background color for this item.
An interface for classes which provider custom handlers for features rendered as part of a map render...
Enable anti-aliasing for map rendering.
StackingPosition stackingPosition() const
Returns the item's stacking position, which specifies where the in the map's stack the item should be...
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
void render(QgsRenderContext &context) const
Renders the annotation to a target render context.
double mapUnitsToLayoutUnits() const
Returns the conversion factor from map units to layout units.
QPointer< QgsLayout > mLayout
void setMapUnits(QgsUnitTypes::DistanceUnit mapUnits)
Set the map units.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
bool enabled() const
Returns whether the item will be drawn.
Contains information relating to a node (i.e.
QString description() const
Returns the descriptive name of the CRS, e.g., "WGS 84" or "GDA 94 / Vicgrid94".
Hide coverage layer in outputs.
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified style entity visitor, causing it to visit all style entities associated with th...
void setSimplifyMethod(const QgsVectorSimplifyMethod &method)
Sets the simplification setting to use when rendering vector layers.
Whether to draw labels which are partially outside of the map view.
void setMoveContentPreviewOffset(double dx, double dy) override
Sets temporary offset for the item, by a specified dx and dy in layout units.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts, annotations, canvases, etc.
void setLabelBoundaryGeometry(const QgsGeometry &boundary)
Sets the label boundary geometry, which restricts where in the rendered map labels are permitted to b...
QgsLayoutItemMap::MapItemFlags mapFlags() const
Returns the map item's flags, which control how the map content is drawn.
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the map's preset crs (coordinate reference system).
QString id() const
Returns the item's ID name.
QgsLayoutItem::Flags itemFlags() const override
Returns the item's flags, which indicate how the item behaves.
QgsRectangle requestedExtent() const
Calculates the extent to request and the yShift of the top-left point in case of rotation.
QList< QgsMapLayer * > layersToRender(const QgsExpressionContext *context=nullptr) const
Returns a list of the layers which will be rendered within this map item, considering any locked laye...
Label blocking region (in map coordinates and CRS).
Single scope for storing variables and functions for use within a QgsExpressionContext.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
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...
static void rotate(double angle, double &x, double &y)
Rotates a point / vector around the origin.
If set, then raster layers will not be drawn as separate tiles. This may improve the appearance in ex...
void predefinedScalesChanged()
Emitted when the list of predefined scales changes.
Enable drawing of vertex markers for layers in editing mode.
The extent is adjusted so that each feature is fully visible.
An individual grid which is drawn above the map content in a QgsLayoutItemMap.
QPolygonF visibleExtentPolygon() const
Returns a polygon representing the current visible map extent, considering map extents and rotation...
void mapRotationChanged(double newRotation)
Emitted when the map's rotation changes.
Use antialiasing when drawing items.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the stored overrides of styles for layers.
Full WKT2 string, conforming to ISO 19162:2018 / OGC 18-010, with all possible nodes and new keyword ...
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
void setRotation(double rotation)
Sets the rotation of the resulting map image, in degrees clockwise.
Contains settings and helpers relating to a render of a QgsLayoutItem.
QString projectionAcronym() const
Returns the projection acronym for the projection used by the CRS.
QgsExpressionContext & expressionContext()
Gets the expression context.
Calculates scale for a given combination of canvas size, map extent, and monitor dpi.
void setUnits(const QgsUnitTypes::LayoutUnit units)
Sets the units for the measurement.
void setAtlasDriven(bool enabled)
Sets whether the map extent will follow the current atlas feature.
QgsLayerTree * layerTreeRoot() const
Returns pointer to the root (invisible) node of the project's layer tree.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
static QgsLayoutMeasurement decodeMeasurement(const QString &string)
Decodes a measurement from a string.
#define Q_NOWARN_DEPRECATED_POP
void paint(QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget) override
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...
void setBackgroundColor(const QColor &color)
Sets the background color of the map.
double mapRotation(QgsLayoutObject::PropertyValueType valueType=QgsLayoutObject::EvaluatedValue) const
Returns the rotation used for drawing the map within the layout item, in degrees clockwise.
bool nextExportPart() override
Moves to the next export part for a multi-layered export item, during a multi-layered export...
Return the current evaluated value for the property.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets the global configuration of the labeling engine.
void setLabelMargin(const QgsLayoutMeasurement &margin)
Sets the margin from the map edges in which no labels may be placed.
QgsCoordinateReferenceSystem mapPositionCrs() const
Returns the CRS of the map position, or an invalid CRS if the annotation does not have a fixed map po...
Contains information about the context of a rendering operation.
void removeLabelBlockingItem(QgsLayoutItem *item)
Removes the specified layout item from the map's "label blocking items".
Force output in vector format where possible, even if items require rasterization to keep their corre...
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
ExportLayerBehavior
Behavior of item when exporting to layered outputs.
double length() const
Returns the length of the measurement.
void setMapRotation(double rotation)
Sets the rotation for the map - this does not affect the layout item shape, only the way the map is d...
void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties) override
QPainter * painter()
Returns the destination QPainter for the render operation.
void layersWillBeRemoved(const QStringList &layerIds)
Emitted when one or more layers are about to be removed from the registry.
virtual bool visitEnter(const QgsStyleEntityVisitorInterface::Node &node)
Called when the visitor starts visiting a node.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
void setSelectionColor(const QColor &color)
Sets color that is used for drawing of selected vector features.
bool containsWmsLayer() const
Returns true if the map contains a WMS layer.
void writeXml(QDomElement &styleElement) const
Write style configuration (for project file writing)
QgsLayoutItemMapOverview * overview()
Returns the map item's first overview.
Enable advanced effects such as blend modes.
bool shouldDrawItem() const
Returns whether the item should be drawn in the current context.
void updateBoundingRect()
Updates the bounding rect of this item. Call this function before doing any changes related to annota...
void refreshed()
Emitted when the layout has been refreshed and items should also be refreshed and updated...
void setYMaximum(double y)
Set the maximum y value.
The current scale of the map is used for each feature of the atlas.
double scale() const
Returns the map scale.
friend class QgsLayoutItemMapGrid
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
Stores global configuration for labeling engine.
virtual QString uuid() const
Returns the item identification string.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
This class represents a coordinate reference system (CRS).
void assignFreeId()
Sets the map id() to a number not yet used in the layout.
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
void setLayers(const QList< QgsMapLayer *> &layers)
Set list of layers for map rendering.
void stopLayeredExport() override
Stops a multi-layer export operation.
void setPathResolver(const QgsPathResolver &resolver)
Sets the path resolver for conversion between relative and absolute paths during rendering operations...
bool readXml(const QDomNode &node)
Restores state from the given DOM node.
double yMaximum() const
Returns the y maximum value (top side of rectangle).
void layerStyleOverridesChanged()
Emitted when layer style overrides are changed...
Enable vector simplification and other rendering optimizations.
QString mapLayerId
Associated map layer ID, or an empty string if this export layer is not associated with a map layer...
void addRenderedFeatureHandler(QgsRenderedFeatureHandlerInterface *handler)
Adds a rendered feature handler to use while rendering the map settings.
Item overrides the default layout item painting method.
Custom exception class for Coordinate Reference System related exceptions.
QPolygonF visiblePolygon() const
Returns the visible area as a polygon (may be rotated)
bool atlasDriven() const
Returns whether the map extent is set to follow the current atlas feature.
bool readPropertiesFromElement(const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context) override
Sets item state from a DOM element.
QgsPointXY center() const
Returns the center point of the rectangle.
ExportLayerBehavior exportLayerBehavior() const override
Returns the behavior of this item during exporting to layered exports (e.g.
void zoomToExtent(const QgsRectangle &extent)
Zooms the map so that the specified extent is fully visible within the map item.
AtlasScalingMode
Scaling modes used for the serial rendering (atlas)
void addRenderedFeatureHandler(QgsRenderedFeatureHandlerInterface *handler)
Adds a rendered feature handler to use while rendering the map.
bool isLabelBlockingItem(QgsLayoutItem *item) const
Returns true if the specified item is a "label blocking item".
Q_DECL_DEPRECATED int numberExportLayers() const override
Returns the number of layers that this item requires for exporting during layered exports (e...
void setMapFlags(QgsLayoutItemMap::MapItemFlags flags)
Sets the map item's flags, which control how the map content is drawn.
QString encodeMeasurement() const
Encodes the layout measurement to a string.
TYPE * resolve(const QgsProject *project)
Resolves the map layer by attempting to find a layer with matching ID within a project.
bool writeXml(QDomNode &node, QDomDocument &doc) const
Stores state to the given Dom node in the given document.
void changed()
Emitted when the object's properties change.
Rendering layer symbology.
Contains details of a particular export layer relating to a layout item.
DataDefinedProperty
Data defined properties for different item types.
QgsLayoutMeasurement labelMargin() const
Returns the margin from the map edges in which no labels may be placed.
void setScale(double scale, bool forceUpdate=true)
Sets new map scale and changes only the map extent.
void refresh() override
Refreshes the item, causing a recalculation of any property overrides and recalculation of its positi...
void finalizeRestoreFromXml() override
Called after all pending items have been restored from XML.
QRectF boundingRect() const override
void renderSynchronously()
Render the map synchronously in this thread.
Whether to render unplaced labels in the map view.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
QString authid() const
Returns the authority identifier for the CRS.
void setXMinimum(double x)
Set the minimum x value.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
Render above all map layers and labels.
QString toWkt(WktVariant variant=WKT1_GDAL, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
double height() const
Returns the height of the rectangle.
A scale is chosen from the predefined scales.
void setFlag(Flag f, bool enabled=true)
Sets whether a particual flag is enabled.
Labels should be rendered in individual stages by map layer. This allows separation of labels belongi...
When rendering map items to multi-layered exports, render labels belonging to different layers into s...
double calculate(const QgsRectangle &mapExtent, double canvasWidth) const
Calculate the scale denominator.
void setLabelBlockingRegions(const QList< QgsLabelBlockingRegion > ®ions)
Sets a list of regions to avoid placing labels within.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QgsLayoutItemMapGrid * grid()
Returns the map item's first grid.