43#include <QStyleOptionGraphicsItem>
51 mBackgroundUpdateTimer =
new QTimer(
this );
52 mBackgroundUpdateTimer->setSingleShot(
true );
53 connect( mBackgroundUpdateTimer, &QTimer::timeout,
this, &QgsLayoutItemMap::recreateCachedImageInBackground );
57 setCacheMode( QGraphicsItem::NoCache );
64 mGridStack = std::make_unique< QgsLayoutItemMapGridStack >(
this );
65 mOverviewStack = std::make_unique< QgsLayoutItemMapOverviewStack >(
this );
98 mPainterJob->cancel();
123 QList<QgsLayoutItemMap *> mapsList;
124 mLayout->layoutItems( mapsList );
133 if ( map->mMapId == mMapId )
136 maxId = std::max( maxId, map->mMapId );
141 mLayout->itemsModel()->updateItemDisplayName(
this );
153 return tr(
"Map %1" ).arg( mMapId );
165 mCachedLayerStyleOverridesPresetName.clear();
169 updateAtlasFeature();
174 if ( rect().isEmpty() )
179 calculator.
setDpi( 25.4 );
186 double currentScaleDenominator =
scale();
193 double scaleRatio = scaleDenominator / currentScaleDenominator;
194 mExtent.
scale( scaleRatio );
196 if ( mAtlasDriven && mAtlasScalingMode ==
Fixed )
203 calculator.
setDpi( 25.4 );
204 scaleRatio = scaleDenominator / calculator.
calculate( mExtent, rect().width() );
205 mExtent.
scale( scaleRatio );
229 QRectF currentRect = rect();
231 double newHeight = currentRect.width() * mExtent.
height() / mExtent.
width();
243 double currentWidthHeightRatio = 1.0;
244 if ( !currentExtent.
isNull() )
245 currentWidthHeightRatio = currentExtent.
width() / currentExtent.
height();
247 currentWidthHeightRatio = rect().width() / rect().height();
248 double newWidthHeightRatio = newExtent.
width() / newExtent.
height();
250 if ( currentWidthHeightRatio < newWidthHeightRatio )
253 double newHeight = newExtent.
width() / currentWidthHeightRatio;
254 double deltaHeight = newHeight - newExtent.
height();
261 double newWidth = currentWidthHeightRatio * newExtent.
height();
262 double deltaWidth = newWidth - newExtent.
width();
267 if ( mExtent == newExtent )
286QPolygonF QgsLayoutItemMap::calculateVisibleExtentPolygon(
bool includeClipping )
const
289 mapPolygon( mExtent, poly );
291 if ( includeClipping && mItemClippingSettings->
isActive() )
305 return calculateVisibleExtentPolygon(
true );
313 return mLayout->project()->crs();
328 return _qgis_listRefToRaw( mLayers );
333 mLayers = _qgis_listRawToRef(
layers );
338 if ( overrides == mLayerStyleOverrides )
341 mLayerStyleOverrides = overrides;
348 mLayerStyleOverrides.clear();
355 mLayerStyleOverrides.insert( layer->id(), style.
xmlData() );
362 if ( mFollowVisibilityPreset == follow )
365 mFollowVisibilityPreset = follow;
367 if ( !mFollowVisibilityPresetName.isEmpty() )
368 emit
themeChanged( mFollowVisibilityPreset ? mFollowVisibilityPresetName : QString() );
373 if ( name == mFollowVisibilityPresetName )
376 mFollowVisibilityPresetName = name;
377 if ( mFollowVisibilityPreset )
383 mLastRenderedImageOffsetX -= dx;
384 mLastRenderedImageOffsetY -= dy;
387 transformShift( dx, dy );
411 double mapY = mExtent.
yMinimum() + ( 1 - ( point.y() / rect().height() ) ) * ( mExtent.
yMaximum() - mExtent.
yMinimum() );
417 centerX = mapX + ( centerX - mapX ) * ( 1.0 / factor );
418 centerY = mapY + ( centerY - mapY ) * ( 1.0 / factor );
420 double newIntervalX, newIntervalY;
437 if ( mAtlasDriven && mAtlasScalingMode ==
Fixed )
444 calculator.
setDpi( 25.4 );
445 double scaleRatio =
scale() / calculator.
calculate( mExtent, rect().width() );
446 mExtent.
scale( scaleRatio );
462 if ( layer->dataProvider() && layer->providerType() == QLatin1String(
"wms" ) )
496 if ( mOverviewStack->containsAdvancedEffects() )
502 if ( mGridStack->containsAdvancedEffects() )
514 mMapRotation = rotation;
515 mEvaluatedMapRotation = mMapRotation;
529 mAtlasDriven = enabled;
546 double margin = mAtlasMargin;
554 margin = ddMargin / 100;
566 if ( mGridStack->size() < 1 )
569 mGridStack->addGrid(
grid );
571 return mGridStack->grid( 0 );
576 if ( mOverviewStack->size() < 1 )
579 mOverviewStack->addOverview(
overview );
581 return mOverviewStack->overview( 0 );
592 mapElem.setAttribute( QStringLiteral(
"keepLayerSet" ), QStringLiteral(
"true" ) );
596 mapElem.setAttribute( QStringLiteral(
"keepLayerSet" ), QStringLiteral(
"false" ) );
599 if ( mDrawAnnotations )
601 mapElem.setAttribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"true" ) );
605 mapElem.setAttribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"false" ) );
609 QDomElement extentElem = doc.createElement( QStringLiteral(
"Extent" ) );
614 mapElem.appendChild( extentElem );
618 QDomElement crsElem = doc.createElement( QStringLiteral(
"crs" ) );
620 mapElem.appendChild( crsElem );
624 mapElem.setAttribute( QStringLiteral(
"followPreset" ), mFollowVisibilityPreset ? QStringLiteral(
"true" ) : QStringLiteral(
"false" ) );
625 mapElem.setAttribute( QStringLiteral(
"followPresetName" ), mFollowVisibilityPresetName );
628 mapElem.setAttribute( QStringLiteral(
"mapRotation" ), QString::number( mMapRotation ) );
631 QDomElement layerSetElem = doc.createElement( QStringLiteral(
"LayerSet" ) );
636 QDomElement layerElem = doc.createElement( QStringLiteral(
"Layer" ) );
637 QDomText layerIdText = doc.createTextNode( layerRef.layerId );
638 layerElem.appendChild( layerIdText );
640 layerElem.setAttribute( QStringLiteral(
"name" ), layerRef.name );
641 layerElem.setAttribute( QStringLiteral(
"source" ), layerRef.source );
642 layerElem.setAttribute( QStringLiteral(
"provider" ), layerRef.provider );
644 layerSetElem.appendChild( layerElem );
646 mapElem.appendChild( layerSetElem );
649 if ( mKeepLayerStyles )
651 QDomElement stylesElem = doc.createElement( QStringLiteral(
"LayerStyles" ) );
652 for (
auto styleIt = mLayerStyleOverrides.constBegin(); styleIt != mLayerStyleOverrides.constEnd(); ++styleIt )
654 QDomElement styleElem = doc.createElement( QStringLiteral(
"LayerStyle" ) );
659 styleElem.setAttribute( QStringLiteral(
"layerid" ), ref.
layerId );
660 styleElem.setAttribute( QStringLiteral(
"name" ), ref.
name );
661 styleElem.setAttribute( QStringLiteral(
"source" ), ref.
source );
662 styleElem.setAttribute( QStringLiteral(
"provider" ), ref.
provider );
666 stylesElem.appendChild( styleElem );
668 mapElem.appendChild( stylesElem );
672 mGridStack->writeXml( mapElem, doc, context );
675 mOverviewStack->writeXml( mapElem, doc, context );
678 QDomElement atlasElem = doc.createElement( QStringLiteral(
"AtlasMap" ) );
679 atlasElem.setAttribute( QStringLiteral(
"atlasDriven" ), mAtlasDriven );
680 atlasElem.setAttribute( QStringLiteral(
"scalingMode" ), mAtlasScalingMode );
681 atlasElem.setAttribute( QStringLiteral(
"margin" ),
qgsDoubleToString( mAtlasMargin ) );
682 mapElem.appendChild( atlasElem );
684 mapElem.setAttribute( QStringLiteral(
"labelMargin" ), mLabelMargin.
encodeMeasurement() );
685 mapElem.setAttribute( QStringLiteral(
"mapFlags" ),
static_cast< int>( mMapFlags ) );
687 QDomElement labelBlockingItemsElem = doc.createElement( QStringLiteral(
"labelBlockingItems" ) );
688 for (
const auto &item : std::as_const( mBlockingLabelItems ) )
693 QDomElement blockingItemElem = doc.createElement( QStringLiteral(
"item" ) );
694 blockingItemElem.setAttribute( QStringLiteral(
"uuid" ), item->uuid() );
695 labelBlockingItemsElem.appendChild( blockingItemElem );
697 mapElem.appendChild( labelBlockingItemsElem );
700 mapElem.setAttribute( QStringLiteral(
"isTemporal" ),
isTemporal() ? 1 : 0 );
703 mapElem.setAttribute( QStringLiteral(
"temporalRangeBegin" ),
temporalRange().begin().toString( Qt::ISODate ) );
704 mapElem.setAttribute( QStringLiteral(
"temporalRangeEnd" ),
temporalRange().end().toString( Qt::ISODate ) );
707 mAtlasClippingSettings->
writeXml( mapElem, doc, context );
708 mItemClippingSettings->
writeXml( mapElem, doc, context );
715 mUpdatesEnabled =
false;
718 QDomNodeList extentNodeList = itemElem.elementsByTagName( QStringLiteral(
"Extent" ) );
719 if ( !extentNodeList.isEmpty() )
721 QDomElement extentElem = extentNodeList.at( 0 ).toElement();
722 double xmin, xmax, ymin, ymax;
723 xmin = extentElem.attribute( QStringLiteral(
"xmin" ) ).toDouble();
724 xmax = extentElem.attribute( QStringLiteral(
"xmax" ) ).toDouble();
725 ymin = extentElem.attribute( QStringLiteral(
"ymin" ) ).toDouble();
726 ymax = extentElem.attribute( QStringLiteral(
"ymax" ) ).toDouble();
730 QDomNodeList crsNodeList = itemElem.elementsByTagName( QStringLiteral(
"crs" ) );
732 if ( !crsNodeList.isEmpty() )
734 QDomElement crsElem = crsNodeList.at( 0 ).toElement();
740 mMapRotation = itemElem.attribute( QStringLiteral(
"mapRotation" ), QStringLiteral(
"0" ) ).toDouble();
741 mEvaluatedMapRotation = mMapRotation;
744 mFollowVisibilityPreset = itemElem.attribute( QStringLiteral(
"followPreset" ) ).compare( QLatin1String(
"true" ) ) == 0;
745 mFollowVisibilityPresetName = itemElem.attribute( QStringLiteral(
"followPresetName" ) );
748 QString keepLayerSetFlag = itemElem.attribute( QStringLiteral(
"keepLayerSet" ) );
749 if ( keepLayerSetFlag.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
751 mKeepLayerSet =
true;
755 mKeepLayerSet =
false;
758 QString drawCanvasItemsFlag = itemElem.attribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"true" ) );
759 if ( drawCanvasItemsFlag.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
761 mDrawAnnotations =
true;
765 mDrawAnnotations =
false;
768 mLayerStyleOverrides.clear();
772 QDomNodeList layerSetNodeList = itemElem.elementsByTagName( QStringLiteral(
"LayerSet" ) );
773 if ( !layerSetNodeList.isEmpty() )
775 QDomElement layerSetElem = layerSetNodeList.at( 0 ).toElement();
776 QDomNodeList layerIdNodeList = layerSetElem.elementsByTagName( QStringLiteral(
"Layer" ) );
777 mLayers.reserve( layerIdNodeList.size() );
778 for (
int i = 0; i < layerIdNodeList.size(); ++i )
780 QDomElement layerElem = layerIdNodeList.at( i ).toElement();
781 QString layerId = layerElem.text();
782 QString layerName = layerElem.attribute( QStringLiteral(
"name" ) );
783 QString layerSource = layerElem.attribute( QStringLiteral(
"source" ) );
784 QString layerProvider = layerElem.attribute( QStringLiteral(
"provider" ) );
786 QgsMapLayerRef ref( layerId, layerName, layerSource, layerProvider );
793 QDomNodeList layerStylesNodeList = itemElem.elementsByTagName( QStringLiteral(
"LayerStyles" ) );
794 mKeepLayerStyles = !layerStylesNodeList.isEmpty();
795 if ( mKeepLayerStyles )
797 QDomElement layerStylesElem = layerStylesNodeList.at( 0 ).toElement();
798 QDomNodeList layerStyleNodeList = layerStylesElem.elementsByTagName( QStringLiteral(
"LayerStyle" ) );
799 for (
int i = 0; i < layerStyleNodeList.size(); ++i )
801 const QDomElement &layerStyleElement = layerStyleNodeList.at( i ).toElement();
802 QString layerId = layerStyleElement.attribute( QStringLiteral(
"layerid" ) );
803 QString layerName = layerStyleElement.attribute( QStringLiteral(
"name" ) );
804 QString layerSource = layerStyleElement.attribute( QStringLiteral(
"source" ) );
805 QString layerProvider = layerStyleElement.attribute( QStringLiteral(
"provider" ) );
806 QgsMapLayerRef ref( layerId, layerName, layerSource, layerProvider );
810 style.
readXml( layerStyleElement );
816 mNumCachedLayers = 0;
817 mCacheInvalidated =
true;
820 mOverviewStack->readXml( itemElem, doc, context );
823 mGridStack->readXml( itemElem, doc, context );
826 QDomNodeList atlasNodeList = itemElem.elementsByTagName( QStringLiteral(
"AtlasMap" ) );
827 if ( !atlasNodeList.isEmpty() )
829 QDomElement atlasElem = atlasNodeList.at( 0 ).toElement();
830 mAtlasDriven = ( atlasElem.attribute( QStringLiteral(
"atlasDriven" ), QStringLiteral(
"0" ) ) != QLatin1String(
"0" ) );
831 if ( atlasElem.hasAttribute( QStringLiteral(
"fixedScale" ) ) )
833 mAtlasScalingMode = ( atlasElem.attribute( QStringLiteral(
"fixedScale" ), QStringLiteral(
"0" ) ) != QLatin1String(
"0" ) ) ?
Fixed :
Auto;
835 else if ( atlasElem.hasAttribute( QStringLiteral(
"scalingMode" ) ) )
837 mAtlasScalingMode =
static_cast<AtlasScalingMode>( atlasElem.attribute( QStringLiteral(
"scalingMode" ) ).toInt() );
839 mAtlasMargin = atlasElem.attribute( QStringLiteral(
"margin" ), QStringLiteral(
"0.1" ) ).toDouble();
844 mMapFlags =
static_cast< MapItemFlags
>( itemElem.attribute( QStringLiteral(
"mapFlags" ),
nullptr ).toInt() );
847 mBlockingLabelItems.clear();
848 mBlockingLabelItemUuids.clear();
849 QDomNodeList labelBlockingNodeList = itemElem.elementsByTagName( QStringLiteral(
"labelBlockingItems" ) );
850 if ( !labelBlockingNodeList.isEmpty() )
852 QDomElement blockingItems = labelBlockingNodeList.at( 0 ).toElement();
853 QDomNodeList labelBlockingNodeList = blockingItems.childNodes();
854 for (
int i = 0; i < labelBlockingNodeList.size(); ++i )
856 const QDomElement &itemBlockingElement = labelBlockingNodeList.at( i ).toElement();
857 const QString itemUuid = itemBlockingElement.attribute( QStringLiteral(
"uuid" ) );
858 mBlockingLabelItemUuids << itemUuid;
862 mAtlasClippingSettings->
readXml( itemElem, doc, context );
863 mItemClippingSettings->
readXml( itemElem, doc, context );
868 setIsTemporal( itemElem.attribute( QStringLiteral(
"isTemporal" ) ).toInt() );
871 const QDateTime begin = QDateTime::fromString( itemElem.attribute( QStringLiteral(
"temporalRangeBegin" ) ), Qt::ISODate );
872 const QDateTime end = QDateTime::fromString( itemElem.attribute( QStringLiteral(
"temporalRangeEnd" ) ), Qt::ISODate );
876 mUpdatesEnabled =
true;
882 if ( mItemClippingSettings->
isActive() )
893 if ( !
mLayout || !painter || !painter->device() || !mUpdatesEnabled )
902 QRectF thisPaintRect = rect();
908 if (
mLayout->renderContext().isPreviewRender() )
911 painter->setClipRect( thisPaintRect );
912 if ( !mCacheFinalImage || mCacheFinalImage->isNull() )
915 painter->setBrush( QBrush( QColor( 125, 125, 125, 125 ) ) );
916 painter->drawRect( thisPaintRect );
917 painter->setBrush( Qt::NoBrush );
919 messageFont.setPointSize( 12 );
920 painter->setFont( messageFont );
921 painter->setPen( QColor( 255, 255, 255, 255 ) );
922 painter->drawText( thisPaintRect, Qt::AlignCenter | Qt::AlignHCenter, tr(
"Rendering map" ) );
923 if ( mPainterJob && mCacheInvalidated && !mDrawingPreview )
927 mBackgroundUpdateTimer->start( 1 );
929 else if ( !mPainterJob && !mDrawingPreview )
933 mBackgroundUpdateTimer->start( 1 );
938 if ( mCacheInvalidated && !mDrawingPreview )
942 mBackgroundUpdateTimer->start( 1 );
947 double imagePixelWidth = mCacheFinalImage->width();
948 double scale = rect().width() / imagePixelWidth;
952 painter->translate( mLastRenderedImageOffsetX + mXOffset, mLastRenderedImageOffsetY + mYOffset );
954 painter->drawImage( 0, 0, *mCacheFinalImage );
959 painter->setClipRect( thisPaintRect, Qt::NoClip );
961 mOverviewStack->drawItems( painter,
false );
962 mGridStack->drawItems( painter );
964 drawMapFrame( painter );
972 QPaintDevice *paintDevice = painter->device();
980 painter->setRenderHint( QPainter::LosslessImageRendering,
true );
987 int widthInPixels =
static_cast< int >( std::round(
boundingRect().width() * layoutUnitsInInches * destinationDpi ) );
988 int heightInPixels =
static_cast< int >( std::round(
boundingRect().height() * layoutUnitsInInches * destinationDpi ) );
989 QImage image = QImage( widthInPixels, heightInPixels, QImage::Format_ARGB32 );
991 image.fill( Qt::transparent );
992 image.setDotsPerMeterX(
static_cast< int >( std::round( 1000 * destinationDpi / 25.4 ) ) );
993 image.setDotsPerMeterY(
static_cast< int >( std::round( 1000 * destinationDpi / 25.4 ) ) );
994 double dotsPerMM = destinationDpi / 25.4;
995 QPainter p( &image );
998 QRect imagePaintRect(
static_cast< int >( std::round( tl.x() * dotsPerMM ) ),
999 static_cast< int >( std::round( tl.y() * dotsPerMM ) ),
1000 static_cast< int >( std::round( thisPaintRect.width() * dotsPerMM ) ),
1001 static_cast< int >( std::round( thisPaintRect.height() * dotsPerMM ) ) );
1002 p.setClipRect( imagePaintRect );
1004 p.translate( imagePaintRect.topLeft() );
1008 if ( shouldDrawPart( Background ) )
1010 p.scale( dotsPerMM, dotsPerMM );
1011 drawMapBackground( &p );
1012 p.scale( 1.0 / dotsPerMM, 1.0 / dotsPerMM );
1015 drawMap( &p, cExtent, imagePaintRect.size(), image.logicalDpiX() );
1020 p.scale( dotsPerMM, dotsPerMM );
1022 if ( shouldDrawPart( OverviewMapExtent ) )
1024 mOverviewStack->drawItems( &p,
false );
1026 if ( shouldDrawPart( Grid ) )
1028 mGridStack->drawItems( &p );
1033 painter->scale( 1 / dotsPerMM, 1 / dotsPerMM );
1034 painter->drawImage( QPointF( -tl.x()* dotsPerMM, -tl.y() * dotsPerMM ), image );
1035 painter->scale( dotsPerMM, dotsPerMM );
1040 if ( shouldDrawPart( Background ) )
1042 drawMapBackground( painter );
1046 painter->setClipRect( thisPaintRect );
1051 painter->translate( mXOffset, mYOffset );
1053 double dotsPerMM = paintDevice->logicalDpiX() / 25.4;
1055 painter->scale( 1 / dotsPerMM, 1 / dotsPerMM );
1057 if ( mCurrentExportPart != NotLayered )
1059 if ( !mStagedRendererJob )
1061 createStagedRenderJob( cExtent, size, paintDevice->logicalDpiX() );
1064 mStagedRendererJob->renderCurrentPart( painter );
1068 drawMap( painter, cExtent, size, paintDevice->logicalDpiX() );
1072 painter->setClipRect( thisPaintRect, Qt::NoClip );
1074 if ( shouldDrawPart( OverviewMapExtent ) )
1076 mOverviewStack->drawItems( painter,
false );
1078 if ( shouldDrawPart( Grid ) )
1080 mGridStack->drawItems( painter );
1085 if ( shouldDrawPart( Frame ) )
1087 drawMapFrame( painter );
1098 + ( layerCount + ( layerCount ? 1 : 0 ) )
1099 + ( mGridStack->hasEnabledItems() ? 1 : 0 )
1100 + ( mOverviewStack->hasEnabledItems() ? 1 : 0 )
1106 mCurrentExportPart = Start;
1108 mExportThemes = !mFollowVisibilityPreset ?
mLayout->renderContext().exportThemes() : QStringList();
1109 mExportThemeIt = mExportThemes.begin();
1114 mCurrentExportPart = NotLayered;
1115 mExportThemes.clear();
1116 mExportThemeIt = mExportThemes.begin();
1121 switch ( mCurrentExportPart )
1126 mCurrentExportPart = Background;
1132 mCurrentExportPart = Layer;
1136 if ( mStagedRendererJob )
1138 if ( mStagedRendererJob->nextPart() )
1142 mExportLabelingResults.reset( mStagedRendererJob->takeLabelingResults() );
1143 mStagedRendererJob.reset();
1147 if ( mExportThemeIt != mExportThemes.end() && ++mExportThemeIt != mExportThemes.end() )
1153 if ( mGridStack->hasEnabledItems() )
1155 mCurrentExportPart = Grid;
1161 for (
int i = 0; i < mOverviewStack->size(); ++i )
1166 mCurrentExportPart = OverviewMapExtent;
1172 case OverviewMapExtent:
1175 mCurrentExportPart = Frame;
1182 if ( isSelected() && !
mLayout->renderContext().isPreviewRender() )
1184 mCurrentExportPart = SelectionBoxes;
1189 case SelectionBoxes:
1190 mCurrentExportPart = End;
1211 switch ( mCurrentExportPart )
1221 if ( !mExportThemes.empty() && mExportThemeIt != mExportThemes.end() )
1224 if ( mStagedRendererJob )
1226 switch ( mStagedRendererJob->currentStage() )
1230 detail.
mapLayerId = mStagedRendererJob->currentLayerId();
1231 detail.
compositionMode = mStagedRendererJob->currentLayerCompositionMode();
1232 detail.
opacity = mStagedRendererJob->currentLayerOpacity();
1238 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), layer->name() );
1240 else if (
mLayout->project()->mainAnnotationLayer()->id() == detail.
mapLayerId )
1246 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), tr(
"Annotations" ) );
1251 const QList<QgsLayoutItemMapOverview *> res = mOverviewStack->asList();
1257 if ( item->mapLayer() && detail.
mapLayerId == item->mapLayer()->id() )
1260 detail.
name = QStringLiteral(
"%1 (%2): %3" ).arg(
displayName(), detail.
mapTheme, item->mapLayer()->name() );
1262 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), item->mapLayer()->name() );
1271 detail.
mapLayerId = mStagedRendererJob->currentLayerId();
1277 detail.
name = tr(
"%1: %2 (Labels)" ).arg(
displayName(), layer->name() );
1312 case OverviewMapExtent:
1320 case SelectionBoxes:
1335void QgsLayoutItemMap::drawMap( QPainter *painter,
const QgsRectangle &extent, QSizeF size,
double dpi )
1349 if ( shouldDrawPart( OverviewMapExtent ) )
1351 ms.setLayers( mOverviewStack->modifyMapLayerList( ms.layers() ) );
1355#ifdef HAVE_SERVER_PYTHON_PLUGINS
1356 job.setFeatureFilterProvider(
mLayout->renderContext().featureFilterProvider() );
1362 job.renderSynchronously();
1364 mExportLabelingResults.reset( job.takeLabelingResults() );
1366 mRenderingErrors = job.errors();
1369void QgsLayoutItemMap::recreateCachedImageInBackground()
1375 QPainter *oldPainter = mPainter.release();
1376 QImage *oldImage = mCacheRenderingImage.release();
1379 oldJob->deleteLater();
1387 mCacheRenderingImage.reset(
nullptr );
1391 Q_ASSERT( !mPainterJob );
1392 Q_ASSERT( !mPainter );
1393 Q_ASSERT( !mCacheRenderingImage );
1399 int w =
static_cast< int >( std::round( widthLayoutUnits * mPreviewScaleFactor ) );
1400 int h =
static_cast< int >( std::round( heightLayoutUnits * mPreviewScaleFactor ) );
1403 if ( w > 5000 || h > 5000 )
1408 h =
static_cast< int>( std::round( w * heightLayoutUnits / widthLayoutUnits ) );
1413 w =
static_cast< int >( std::round( h * widthLayoutUnits / heightLayoutUnits ) );
1417 if ( w <= 0 || h <= 0 )
1420 mCacheRenderingImage.reset(
new QImage( w, h, QImage::Format_ARGB32 ) );
1423 mCacheRenderingImage->setDotsPerMeterX(
static_cast< int >( std::round( 1000 * w / widthLayoutUnits ) ) );
1424 mCacheRenderingImage->setDotsPerMeterY(
static_cast< int >( std::round( 1000 * h / heightLayoutUnits ) ) );
1427 mCacheRenderingImage->fill( QColor( 255, 255, 255, 0 ).rgba() );
1432 if ( mItemClippingSettings->
isActive() )
1434 QPainter p( mCacheRenderingImage.get() );
1436 p.setPen( Qt::NoPen );
1438 p.scale( mCacheRenderingImage->width() / widthLayoutUnits, mCacheRenderingImage->height() / heightLayoutUnits );
1448 mCacheInvalidated =
false;
1449 mPainter.reset(
new QPainter( mCacheRenderingImage.get() ) );
1452 if ( shouldDrawPart( OverviewMapExtent ) )
1454 settings.setLayers( mOverviewStack->modifyMapLayerList( settings.layers() ) );
1459 mPainterJob->start();
1471 mDrawingPreview =
false;
1494 if (
layout()->renderContext().isPreviewRender() )
1497 jobMapSettings.
setRotation( mEvaluatedMapRotation );
1501 if ( includeLayerSettings )
1506 if ( !
mLayout->project()->mainAnnotationLayer()->isEmpty() )
1509 layers.insert( 0,
mLayout->project()->mainAnnotationLayer() );
1516 if ( !
mLayout->renderContext().isPreviewRender() )
1559 if ( mEvaluatedLabelMargin.
length() > 0 )
1562 visiblePoly.append( visiblePoly.at( 0 ) );
1563 const double layoutLabelMargin =
mLayout->convertToLayoutUnits( mEvaluatedLabelMargin );
1564 const double layoutLabelMarginInMapUnits = layoutLabelMargin / rect().width() * jobMapSettings.
extent().
width();
1566 mapBoundaryGeom = mapBoundaryGeom.
buffer( -layoutLabelMarginInMapUnits, 0 );
1567 labelBoundary = mapBoundaryGeom;
1570 if ( !mBlockingLabelItems.isEmpty() )
1583 if ( mAtlasClippingSettings->
enabled() &&
mLayout->reportContext().feature().isValid() )
1594 if ( !labelBoundary.
isEmpty() )
1596 labelBoundary = clipGeom.
intersection( labelBoundary );
1600 labelBoundary = clipGeom;
1605 if ( mItemClippingSettings->
isActive() )
1614 const double layoutLabelMargin =
mLayout->convertToLayoutUnits( mEvaluatedLabelMargin );
1615 const double layoutLabelMarginInMapUnits = layoutLabelMargin / rect().width() * jobMapSettings.
extent().
width();
1617 mapBoundaryGeom = mapBoundaryGeom.
buffer( -layoutLabelMarginInMapUnits, 0 );
1618 if ( !labelBoundary.
isEmpty() )
1620 labelBoundary = mapBoundaryGeom.
intersection( labelBoundary );
1624 labelBoundary = mapBoundaryGeom;
1630 if ( !labelBoundary.
isNull() )
1633 return jobMapSettings;
1640 mBlockingLabelItems.clear();
1641 for (
const QString &
uuid : std::as_const( mBlockingLabelItemUuids ) )
1650 mOverviewStack->finalizeRestoreFromXml();
1651 mGridStack->finalizeRestoreFromXml();
1663 return mCurrentRectangle;
1677 const double mapScale =
scale();
1701 QVariantList layersIds;
1711 const QList<QgsMapLayer *> layersInMap =
layersToRender( &context );
1713 layersIds.reserve( layersInMap.count() );
1714 layers.reserve( layersInMap.count() );
1717 layersIds << layer->id();
1723 scope->
addFunction( QStringLiteral(
"is_layer_visible" ),
new QgsExpressionContextUtils::GetLayerVisibility( layersInMap,
scale() ) );
1742 if ( extentWidth <= 0 )
1746 return rect().width() / extentWidth;
1751 double dx = mXOffset;
1752 double dy = mYOffset;
1753 transformShift( dx, dy );
1754 QPolygonF poly = calculateVisibleExtentPolygon(
false );
1755 poly.translate( -dx, -dy );
1761 if ( !mBlockingLabelItems.contains( item ) )
1762 mBlockingLabelItems.append( item );
1769 mBlockingLabelItems.removeAll( item );
1776 return mBlockingLabelItems.contains( item );
1781 return mPreviewLabelingResults.get();
1790 if ( mOverviewStack )
1792 for (
int i = 0; i < mOverviewStack->size(); ++i )
1794 if ( mOverviewStack->item( i )->accept( visitor ) )
1801 for (
int i = 0; i < mGridStack->size(); ++i )
1803 if ( mGridStack->item( i )->accept( visitor ) )
1816 mRenderedFeatureHandlers.append( handler );
1821 mRenderedFeatureHandlers.removeAll( handler );
1827 if ( mapPoly.empty() )
1829 return QPointF( 0, 0 );
1834 double dx = mapCoords.x() - rotationPoint.
x();
1835 double dy = mapCoords.y() - rotationPoint.
y();
1837 QgsPointXY backRotatedCoords( rotationPoint.
x() + dx, rotationPoint.
y() + dy );
1840 double xItem = rect().width() * ( backRotatedCoords.
x() - unrotatedExtent.
xMinimum() ) / unrotatedExtent.
width();
1841 double yItem = rect().height() * ( 1 - ( backRotatedCoords.
y() - unrotatedExtent.
yMinimum() ) / unrotatedExtent.
height() );
1842 return QPointF( xItem, yItem );
1856 mapPolygon( newExtent, poly );
1857 QRectF bRect = poly.boundingRect();
1871 mCacheInvalidated =
true;
1877 QRectF rectangle = rect();
1878 double frameExtension =
frameEnabled() ? pen().widthF() / 2.0 : 0.0;
1880 double topExtension = 0.0;
1881 double rightExtension = 0.0;
1882 double bottomExtension = 0.0;
1883 double leftExtension = 0.0;
1886 mGridStack->calculateMaxGridExtension( topExtension, rightExtension, bottomExtension, leftExtension );
1888 topExtension = std::max( topExtension, frameExtension );
1889 rightExtension = std::max( rightExtension, frameExtension );
1890 bottomExtension = std::max( bottomExtension, frameExtension );
1891 leftExtension = std::max( leftExtension, frameExtension );
1893 rectangle.setLeft( rectangle.left() - leftExtension );
1894 rectangle.setRight( rectangle.right() + rightExtension );
1895 rectangle.setTop( rectangle.top() - topExtension );
1896 rectangle.setBottom( rectangle.bottom() + bottomExtension );
1897 if ( rectangle != mCurrentRectangle )
1899 prepareGeometryChange();
1900 mCurrentRectangle = rectangle;
1928 refreshMapExtents( &context );
1930 if ( mExtent != beforeExtent )
1937 refreshLabelMargin(
false );
1941 const QString previousTheme = mLastEvaluatedThemeName.isEmpty() ? mFollowVisibilityPresetName : mLastEvaluatedThemeName;
1943 if ( mLastEvaluatedThemeName != previousTheme )
1961 mCacheInvalidated =
true;
1966void QgsLayoutItemMap::layersAboutToBeRemoved(
const QList<QgsMapLayer *> &layers )
1968 if ( !mLayers.isEmpty() || mLayerStyleOverrides.isEmpty() )
1972 mLayerStyleOverrides.remove( layer->id() );
1974 _qgis_removeLayers( mLayers,
layers );
1978void QgsLayoutItemMap::painterJobFinished()
1981 mPreviewLabelingResults.reset( mPainterJob->takeLabelingResults() );
1982 mPainterJob.reset(
nullptr );
1983 mPainter.reset(
nullptr );
1984 mCacheFinalImage = std::move( mCacheRenderingImage );
1985 mLastRenderedImageOffsetX = 0;
1986 mLastRenderedImageOffsetY = 0;
1992void QgsLayoutItemMap::shapeChanged()
1997 double w = rect().width();
1998 double h = rect().height();
2001 double newWidth = mExtent.
width();
2003 double newHeight = newWidth * h / w;
2008 refreshMapExtents();
2015void QgsLayoutItemMap::mapThemeChanged(
const QString &theme )
2017 if ( theme == mCachedLayerStyleOverridesPresetName )
2018 mCachedLayerStyleOverridesPresetName.clear();
2021void QgsLayoutItemMap::currentMapThemeRenamed(
const QString &theme,
const QString &newTheme )
2023 if ( theme == mFollowVisibilityPresetName )
2025 mFollowVisibilityPresetName = newTheme;
2029void QgsLayoutItemMap::connectUpdateSlot()
2037 this, &QgsLayoutItemMap::layersAboutToBeRemoved );
2041 if ( layers().isEmpty() )
2070 if ( mAtlasScalingMode == Predefined )
2071 updateAtlasFeature();
2077 QPolygonF thisExtent = calculateVisibleExtentPolygon(
false );
2078 QTransform mapTransform;
2079 QPolygonF thisRectPoly = QPolygonF( QRectF( 0, 0, rect().width(), rect().height() ) );
2081 thisRectPoly.pop_back();
2082 thisExtent.pop_back();
2084 QPolygonF thisItemPolyInLayout = mapToScene( thisRectPoly );
2087 QTransform::quadToQuad( thisItemPolyInLayout, thisExtent, mapTransform );
2088 return mapTransform;
2091QList<QgsLabelBlockingRegion> QgsLayoutItemMap::createLabelBlockingRegions(
const QgsMapSettings & )
const
2094 QList< QgsLabelBlockingRegion > blockers;
2095 blockers.reserve( mBlockingLabelItems.count() );
2096 for (
const auto &item : std::as_const( mBlockingLabelItems ) )
2103 if ( item->property(
"wasVisible" ).isValid() )
2105 if ( !item->property(
"wasVisible" ).toBool() )
2108 else if ( !item->isVisible() )
2111 QPolygonF itemRectInMapCoordinates = mapTransform.map( item->mapToScene( item->rect() ) );
2112 itemRectInMapCoordinates.append( itemRectInMapCoordinates.at( 0 ) );
2121 return mLabelMargin;
2126 mLabelMargin = margin;
2127 refreshLabelMargin(
false );
2130void QgsLayoutItemMap::updateToolTip()
2139 if ( mFollowVisibilityPreset )
2141 presetName = mFollowVisibilityPresetName;
2145 else if ( !mExportThemes.empty() && mExportThemeIt != mExportThemes.end() )
2146 presetName = *mExportThemeIt;
2157 QList<QgsMapLayer *> renderLayers;
2159 QString presetName = themeToRender( *evalContext );
2160 if ( !presetName.isEmpty() )
2162 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
2163 renderLayers =
mLayout->project()->mapThemeCollection()->mapThemeVisibleLayers( presetName );
2165 renderLayers =
mLayout->project()->mapThemeCollection()->masterVisibleLayers();
2167 else if ( !
layers().isEmpty() )
2173 renderLayers =
mLayout->project()->mapThemeCollection()->masterVisibleLayers();
2180 renderLayers.clear();
2182 const QStringList layerNames = ddLayers.split(
'|' );
2184 for (
const QString &name : layerNames )
2186 const QList< QgsMapLayer * > matchingLayers =
mLayout->project()->mapLayersByName( name );
2189 renderLayers << layer;
2198 int removeAt = renderLayers.indexOf(
mLayout->reportContext().layer() );
2199 if ( removeAt != -1 )
2201 renderLayers.removeAt( removeAt );
2206 renderLayers.erase( std::remove_if( renderLayers.begin(), renderLayers.end(), [](
QgsMapLayer * layer )
2208 return !layer || !layer->isValid();
2209 } ), renderLayers.end() );
2211 return renderLayers;
2214QMap<QString, QString> QgsLayoutItemMap::layerStyleOverridesToRender(
const QgsExpressionContext &context )
const
2216 QString presetName = themeToRender( context );
2217 if ( !presetName.isEmpty() )
2219 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
2221 if ( presetName != mCachedLayerStyleOverridesPresetName )
2224 mCachedPresetLayerStyleOverrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( presetName );
2225 mCachedLayerStyleOverridesPresetName = presetName;
2228 return mCachedPresetLayerStyleOverrides;
2231 return QMap<QString, QString>();
2233 else if ( mFollowVisibilityPreset )
2235 QString presetName = mFollowVisibilityPresetName;
2238 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
2240 if ( presetName.isEmpty() || presetName != mCachedLayerStyleOverridesPresetName )
2243 mCachedPresetLayerStyleOverrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( presetName );
2244 mCachedLayerStyleOverridesPresetName = presetName;
2247 return mCachedPresetLayerStyleOverrides;
2250 return QMap<QString, QString>();
2252 else if ( mKeepLayerStyles )
2254 return mLayerStyleOverrides;
2258 return QMap<QString, QString>();
2262QgsRectangle QgsLayoutItemMap::transformedExtent()
const
2264 double dx = mXOffset;
2265 double dy = mYOffset;
2266 transformShift( dx, dy );
2270void QgsLayoutItemMap::mapPolygon(
const QgsRectangle &extent, QPolygonF &poly )
const
2280 poly << QPointF( poly.at( 0 ) );
2292 poly << QPointF( rotationPoint.x() - dx, rotationPoint.y() - dy );
2298 poly << QPointF( rotationPoint.x() - dx, rotationPoint.y() - dy );
2304 poly << QPointF( rotationPoint.x() - dx, rotationPoint.y() - dy );
2310 poly << QPointF( rotationPoint.x() - dx, rotationPoint.y() - dy );
2313 poly << QPointF( poly.at( 0 ) );
2316void QgsLayoutItemMap::transformShift(
double &xShift,
double &yShift )
const
2319 double dxScaled = xShift * mmToMapUnits;
2320 double dyScaled = - yShift * mmToMapUnits;
2335 const QList< QgsAnnotation * > annotations =
mLayout->project()->annotationManager()->annotations();
2336 if ( annotations.isEmpty() )
2346 if ( !annotation || !annotation->isVisible() )
2350 if ( annotation->mapLayer() && !
layers.contains( annotation->mapLayer() ) )
2353 drawAnnotation( annotation, rc );
2367 double itemX, itemY;
2370 QPointF mapPos = layoutMapPosForItem( annotation );
2379 context.
painter()->translate( itemX, itemY );
2382 double dotsPerMM = context.
painter()->device()->logicalDpiX() / 25.4;
2383 context.
painter()->scale( 1 / dotsPerMM, 1 / dotsPerMM );
2385 annotation->
render( context );
2388QPointF QgsLayoutItemMap::layoutMapPosForItem(
const QgsAnnotation *annotation )
const
2391 return QPointF( 0, 0 );
2400 if ( annotationCrs !=
crs() )
2407 t.transformInPlace( mapX, mapY, z );
2417void QgsLayoutItemMap::drawMapFrame( QPainter *p )
2428void QgsLayoutItemMap::drawMapBackground( QPainter *p )
2439bool QgsLayoutItemMap::shouldDrawPart( QgsLayoutItemMap::PartType part )
const
2441 if ( mCurrentExportPart == NotLayered )
2459 return mCurrentExportPart == Layer;
2462 return mCurrentExportPart == Grid && mGridStack->hasEnabledItems();
2464 case OverviewMapExtent:
2465 return mCurrentExportPart == OverviewMapExtent && mOverviewStack->hasEnabledItems();
2470 case SelectionBoxes:
2471 return mCurrentExportPart == SelectionBoxes && isSelected();
2492 bool useDdXMin =
false;
2493 bool useDdXMax =
false;
2494 bool useDdYMin =
false;
2495 bool useDdYMax =
false;
2526 if ( newExtent != mExtent )
2532 double currentWidthHeightRatio = mExtent.
width() / mExtent.
height();
2533 double newWidthHeightRatio = newExtent.
width() / newExtent.
height();
2535 if ( currentWidthHeightRatio < newWidthHeightRatio )
2538 double newHeight = newExtent.
width() / currentWidthHeightRatio;
2539 double deltaHeight = newHeight - newExtent.
height();
2546 double newWidth = currentWidthHeightRatio * newExtent.
height();
2547 double deltaWidth = newWidth - newExtent.
width();
2552 mExtent = newExtent;
2562 newExtent = mExtent;
2565 if ( useDdXMax || useDdXMin || useDdYMax || useDdYMin )
2569 if ( useDdXMin && !useDdXMax )
2575 else if ( !useDdXMin && useDdXMax )
2581 if ( useDdYMin && !useDdYMax )
2587 else if ( !useDdYMin && useDdYMax )
2594 if ( newExtent != mExtent )
2596 mExtent = newExtent;
2613void QgsLayoutItemMap::refreshLabelMargin(
bool updateItem )
2626void QgsLayoutItemMap::updateAtlasFeature()
2645 if ( mAtlasScalingMode ==
Fixed || mAtlasScalingMode ==
Predefined || isPointLayer )
2650 double originalScale = calc.
calculate( originalExtent, rect().width() );
2651 double geomCenterX = ( xa1 + xa2 ) / 2.0;
2652 double geomCenterY = ( ya1 + ya2 ) / 2.0;
2653 QVector<qreal> scales;
2655 if ( !
mLayout->reportContext().predefinedScales().empty() )
2656 scales =
mLayout->reportContext().predefinedScales();
2658 scales =
mLayout->renderContext().predefinedScales();
2660 if ( mAtlasScalingMode ==
Fixed || scales.isEmpty() || ( isPointLayer && mAtlasScalingMode !=
Predefined ) )
2663 double xMin = geomCenterX - originalExtent.
width() / 2.0;
2664 double yMin = geomCenterY - originalExtent.
height() / 2.0;
2667 xMin + originalExtent.
width(),
2668 yMin + originalExtent.
height() );
2672 double newScale = calc.
calculate( newExtent, rect().width() );
2673 newExtent.
scale( originalScale / newScale );
2678 double newWidth = originalExtent.
width();
2679 double newHeight = originalExtent.
height();
2680 for (
int i = 0; i < scales.size(); i++ )
2682 double ratio = scales[i] / originalScale;
2683 newWidth = originalExtent.
width() * ratio;
2684 newHeight = originalExtent.
height() * ratio;
2687 double xMin = geomCenterX - newWidth / 2.0;
2688 double yMin = geomCenterY - newHeight / 2.0;
2696 double newScale = calc.
calculate( newExtent, rect().width() );
2697 newExtent.
scale( scales[i] / newScale );
2707 else if ( mAtlasScalingMode ==
Auto )
2711 double geomRatio = bounds.
width() / bounds.
height();
2712 double mapRatio = originalExtent.
width() / originalExtent.
height();
2715 if ( geomRatio < mapRatio )
2718 double adjWidth = ( mapRatio * bounds.
height() - bounds.
width() ) / 2.0;
2723 else if ( geomRatio > mapRatio )
2726 double adjHeight = ( bounds.
width() / mapRatio - bounds.
height() ) / 2.0;
2732 const double evaluatedAtlasMargin =
atlasMargin();
2733 if ( evaluatedAtlasMargin > 0.0 )
2735 newExtent.
scale( 1 + evaluatedAtlasMargin );
2751 if ( mEvaluatedMapRotation != 0.0 )
2761 double dx = std::max( std::abs( prevCenter.
x() - bounds.
xMinimum() ),
2762 std::abs( prevCenter.
x() - bounds.
xMaximum() ) );
2763 double dy = std::max( std::abs( prevCenter.
y() - bounds.
yMinimum() ),
2764 std::abs( prevCenter.
y() - bounds.
yMaximum() ) );
2767 center.
x() + dx, center.
y() + dy );
2775void QgsLayoutItemMap::createStagedRenderJob(
const QgsRectangle &extent,
const QSizeF size,
double dpi )
2778 settings.
setLayers( mOverviewStack->modifyMapLayerList( settings.
layers() ) );
2780 mStagedRendererJob = std::make_unique< QgsMapRendererStagedRenderJob >( settings,
2783 : QgsMapRendererStagedRenderJob::Flags() );
2784 mStagedRendererJob->start();
2800 this, &QgsLayoutItemMapAtlasClippingSettings::layersAboutToBeRemoved );
2806 return mClipToAtlasFeature;
2811 if (
enabled == mClipToAtlasFeature )
2814 mClipToAtlasFeature =
enabled;
2820 return mFeatureClippingType;
2825 if ( mFeatureClippingType == type )
2828 mFeatureClippingType = type;
2834 return mForceLabelsInsideFeature;
2839 if ( forceInside == mForceLabelsInsideFeature )
2842 mForceLabelsInsideFeature = forceInside;
2848 return mRestrictToLayers;
2853 if ( mRestrictToLayers ==
enabled )
2862 return _qgis_listRefToRaw( mLayersToClip );
2873 QDomElement settingsElem = document.createElement( QStringLiteral(
"atlasClippingSettings" ) );
2874 settingsElem.setAttribute( QStringLiteral(
"enabled" ), mClipToAtlasFeature ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
2875 settingsElem.setAttribute( QStringLiteral(
"forceLabelsInside" ), mForceLabelsInsideFeature ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
2876 settingsElem.setAttribute( QStringLiteral(
"clippingType" ), QString::number(
static_cast<int>( mFeatureClippingType ) ) );
2877 settingsElem.setAttribute( QStringLiteral(
"restrictLayers" ), mRestrictToLayers ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
2880 QDomElement layerSetElem = document.createElement( QStringLiteral(
"layersToClip" ) );
2885 QDomElement layerElem = document.createElement( QStringLiteral(
"Layer" ) );
2886 QDomText layerIdText = document.createTextNode( layerRef.layerId );
2887 layerElem.appendChild( layerIdText );
2889 layerElem.setAttribute( QStringLiteral(
"name" ), layerRef.name );
2890 layerElem.setAttribute( QStringLiteral(
"source" ), layerRef.source );
2891 layerElem.setAttribute( QStringLiteral(
"provider" ), layerRef.provider );
2893 layerSetElem.appendChild( layerElem );
2895 settingsElem.appendChild( layerSetElem );
2897 element.appendChild( settingsElem );
2903 const QDomElement settingsElem = element.firstChildElement( QStringLiteral(
"atlasClippingSettings" ) );
2905 mClipToAtlasFeature = settingsElem.attribute( QStringLiteral(
"enabled" ), QStringLiteral(
"0" ) ).toInt();
2906 mForceLabelsInsideFeature = settingsElem.attribute( QStringLiteral(
"forceLabelsInside" ), QStringLiteral(
"0" ) ).toInt();
2908 mRestrictToLayers = settingsElem.attribute( QStringLiteral(
"restrictLayers" ), QStringLiteral(
"0" ) ).toInt();
2910 mLayersToClip.clear();
2911 QDomNodeList layerSetNodeList = settingsElem.elementsByTagName( QStringLiteral(
"layersToClip" ) );
2912 if ( !layerSetNodeList.isEmpty() )
2914 QDomElement layerSetElem = layerSetNodeList.at( 0 ).toElement();
2915 QDomNodeList layerIdNodeList = layerSetElem.elementsByTagName( QStringLiteral(
"Layer" ) );
2916 mLayersToClip.reserve( layerIdNodeList.size() );
2917 for (
int i = 0; i < layerIdNodeList.size(); ++i )
2919 QDomElement layerElem = layerIdNodeList.at( i ).toElement();
2920 QString layerId = layerElem.text();
2921 QString layerName = layerElem.attribute( QStringLiteral(
"name" ) );
2922 QString layerSource = layerElem.attribute( QStringLiteral(
"source" ) );
2923 QString layerProvider = layerElem.attribute( QStringLiteral(
"provider" ) );
2925 QgsMapLayerRef ref( layerId, layerName, layerSource, layerProvider );
2928 mLayersToClip << ref;
2935void QgsLayoutItemMapAtlasClippingSettings::layersAboutToBeRemoved(
const QList<QgsMapLayer *> &layers )
2937 if ( !mLayersToClip.isEmpty() )
2939 _qgis_removeLayers( mLayersToClip, layers );
2954 return mEnabled && mClipPathSource;
2969 if ( mClipPathSource )
2972 mClipPathSource->refresh();
2981 QgsGeometry clipGeom( mClipPathSource->clipPath() );
2992 QgsGeometry clipGeom( mClipPathSource->clipPath() );
2993 clipGeom.
transform( mMap->sceneTransform().inverted() );
3008 if ( mClipPathSource == item )
3011 if ( mClipPathSource )
3020 mClipPathSource = item;
3022 if ( mClipPathSource )
3031 mClipPathSource->refresh();
3045 return mClipPathSource;
3050 return mFeatureClippingType;
3055 if ( mFeatureClippingType == type )
3058 mFeatureClippingType = type;
3064 return mForceLabelsInsideClipPath;
3069 if ( forceInside == mForceLabelsInsideClipPath )
3072 mForceLabelsInsideClipPath = forceInside;
3078 QDomElement settingsElem = document.createElement( QStringLiteral(
"itemClippingSettings" ) );
3079 settingsElem.setAttribute( QStringLiteral(
"enabled" ), mEnabled ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
3080 settingsElem.setAttribute( QStringLiteral(
"forceLabelsInside" ), mForceLabelsInsideClipPath ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
3081 settingsElem.setAttribute( QStringLiteral(
"clippingType" ), QString::number(
static_cast<int>( mFeatureClippingType ) ) );
3082 if ( mClipPathSource )
3083 settingsElem.setAttribute( QStringLiteral(
"clipSource" ), mClipPathSource->uuid() );
3085 settingsElem.setAttribute( QStringLiteral(
"clipSource" ), QString() );
3087 element.appendChild( settingsElem );
3093 const QDomElement settingsElem = element.firstChildElement( QStringLiteral(
"itemClippingSettings" ) );
3095 mEnabled = settingsElem.attribute( QStringLiteral(
"enabled" ), QStringLiteral(
"0" ) ).toInt();
3096 mForceLabelsInsideClipPath = settingsElem.attribute( QStringLiteral(
"forceLabelsInside" ), QStringLiteral(
"0" ) ).toInt();
3098 mClipPathUuid = settingsElem.attribute( QStringLiteral(
"clipSource" ) );
3105 if ( !mClipPathUuid.isEmpty() )
@ Export
Renderer used for printing or exporting to a file.
@ View
Renderer used for displaying on screen.
@ DrawEditingInfo
Enable drawing of vertex markers for layers in editing mode.
@ UseRenderingOptimization
Enable vector simplification and other rendering optimizations.
@ ForceVectorOutput
Vector graphics should not be cached and drawn as raster images.
@ RenderPartialOutput
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
@ ForceRasterMasks
Force symbol masking to be applied using a raster method. This is considerably faster when compared t...
@ LosslessImageRendering
Render images losslessly whenever possible, instead of the default lossy jpeg rendering used for some...
@ DrawSelection
Whether vector selections should be shown in the rendered map.
@ Antialiasing
Enable anti-aliasing for map rendering.
@ UseAdvancedEffects
Enable layer opacity and blending effects.
@ HighQualityImageTransforms
Enable high quality image transformations, which results in better appearance of scaled or rotated ra...
virtual QPainterPath asQPainterPath() const =0
Returns the geometry represented as a QPainterPath.
QDateTime valueAsDateTime(int key, const QgsExpressionContext &context, const QDateTime &defaultDateTime=QDateTime(), bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a datetime.
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.
Abstract base class for annotation items which are drawn over a map.
QgsCoordinateReferenceSystem mapPositionCrs() const
Returns the CRS of the map position, or an invalid CRS if the annotation does not have a fixed map po...
void render(QgsRenderContext &context) const
Renders the annotation to a target render context.
bool isVisible() const
Returns true if the annotation is visible and should be rendered.
QPointF relativePosition() const
Returns the relative position of the annotation, if it is not attached to a fixed map position.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QgsCoordinateReferenceSystemRegistry * coordinateReferenceSystemRegistry()
Returns the application's coordinate reference system (CRS) registry, which handles known CRS definit...
void userCrsChanged(const QString &id)
Emitted whenever an existing user CRS definition is changed.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QString toProj() const
Returns a Proj string representation of this CRS.
bool readXml(const QDomNode &node)
Restores state from the given DOM node.
QString ellipsoidAcronym() const
Returns the ellipsoid acronym for the ellipsoid used by the CRS.
QString projectionAcronym() const
Returns the projection acronym for the projection used by the CRS.
void updateDefinition()
Updates the definition and parameters of the coordinate reference system to their latest values.
@ WKT_PREFERRED
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
bool writeXml(QDomNode &node, QDomDocument &doc) const
Stores state to the given Dom node in the given document.
QString toWkt(WktVariant variant=WKT1_GDAL, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
QgsProjOperation operation() const
Returns information about the PROJ operation associated with the coordinate reference system,...
Q_GADGET QgsUnitTypes::DistanceUnit mapUnits
Custom exception class for Coordinate Reference System related exceptions.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addFunction(const QString &name, QgsScopedExpressionFunction *function)
Adds a function to the scope.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
void setVariable(const QString &name, const QVariant &value, bool isStatic=false)
Convenience method for setting a variable in the context scope by name name and value.
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.
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
static QgsGeometry fromRect(const QgsRectangle &rect) SIP_HOLDGIL
Creates a new geometry from a QgsRectangle.
static QgsGeometry fromPointXY(const QgsPointXY &point) SIP_HOLDGIL
Creates a new geometry from a QgsPointXY object.
QPolygonF asQPolygonF() const SIP_HOLDGIL
Returns contents of the geometry as a QPolygonF.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters ¶meters=QgsGeometryParameters()) const
Returns a geometry representing the points shared by this geometry and other.
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...
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::GeometryOperationResult rotate(double rotation, const QgsPointXY ¢er)
Rotate this geometry around the Z axis.
Label blocking region (in map coordinates and CRS).
Stores global configuration for labeling engine.
@ UsePartialCandidates
Whether to use also label candidates that are partially outside of the map view.
@ CollectUnplacedLabels
Whether unplaced labels should be collected in the labeling results (regardless of whether they are b...
@ DrawUnplacedLabels
Whether to render unplaced labels as an indicator/warning for users.
void setFlag(Flag f, bool enabled=true)
Sets whether a particual flag is enabled.
Class that stores computed placement from labeling engine.
void layerOrderChanged()
Emitted when the layer order has changed.
Contains settings relating to clipping a layout map by the current atlas feature.
void setFeatureClippingType(QgsMapClippingRegion::FeatureClippingType type)
Sets the feature clipping type to apply when clipping to the current atlas feature.
bool restrictToLayers() const
Returns true if clipping should be restricted to a subset of layers.
QgsLayoutItemMapAtlasClippingSettings(QgsLayoutItemMap *map=nullptr)
Constructor for QgsLayoutItemMapAtlasClippingSettings, with the specified map parent.
bool readXml(const QDomElement &element, const QDomDocument &doc, const QgsReadWriteContext &context)
Sets the setting's state from a DOM document, where element is the DOM node corresponding to a 'Layou...
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Stores settings in a DOM element, where element is the DOM element corresponding to a 'LayoutMap' tag...
void setRestrictToLayers(bool enabled)
Sets whether clipping should be restricted to a subset of layers.
void setLayersToClip(const QList< QgsMapLayer * > &layers)
Sets the list of map layers to clip to the atlas feature.
QList< QgsMapLayer * > layersToClip() const
Returns the list of map layers to clip to the atlas feature.
void setEnabled(bool enabled)
Sets whether the map content should be clipped to the current atlas feature.
void changed()
Emitted when the atlas clipping settings are changed.
bool forceLabelsInsideFeature() const
Returns true if labels should only be placed inside the atlas feature geometry.
bool enabled() const
Returns true if the map content should be clipped to the current atlas feature.
void setForceLabelsInsideFeature(bool forceInside)
Sets whether labels should only be placed inside the atlas feature geometry.
QgsMapClippingRegion::FeatureClippingType featureClippingType() const
Returns the feature clipping type to apply when clipping to the current atlas feature.
An individual grid which is drawn above the map content in a QgsLayoutItemMap.
Contains settings relating to clipping a layout map by another layout item.
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Stores settings in a DOM element, where element is the DOM element corresponding to a 'LayoutMap' tag...
void setForceLabelsInsideClipPath(bool forceInside)
Sets whether labels should only be placed inside the clip path geometry.
void setSourceItem(QgsLayoutItem *item)
Sets the source item which will provide the clipping path for the map.
QgsLayoutItemMapItemClipPathSettings(QgsLayoutItemMap *map=nullptr)
Constructor for QgsLayoutItemMapItemClipPathSettings, with the specified map parent.
bool readXml(const QDomElement &element, const QDomDocument &doc, const QgsReadWriteContext &context)
Sets the setting's state from a DOM document, where element is the DOM node corresponding to a 'Layou...
QgsGeometry clipPathInMapItemCoordinates() const
Returns the clipping path geometry, in the map item's coordinate space.
QgsGeometry clippedMapExtent() const
Returns the geometry to use for clipping the parent map, in the map item's CRS.
QgsLayoutItem * sourceItem()
Returns the source item which will provide the clipping path for the map, or nullptr if no item is se...
void setEnabled(bool enabled)
Sets whether the map content should be clipped to the associated item.
bool forceLabelsInsideClipPath() const
Returns true if labels should only be placed inside the clip path geometry.
void finalizeRestoreFromXml()
To be called after all pending items have been restored from XML.
QgsMapClippingRegion::FeatureClippingType featureClippingType() const
Returns the feature clipping type to apply when clipping to the associated item.
bool enabled() const
Returns true if the map content should be clipped to the associated item.
QgsMapClippingRegion toMapClippingRegion() const
Returns the clip path as a map clipping region.
void changed()
Emitted when the item clipping settings are changed.
void setFeatureClippingType(QgsMapClippingRegion::FeatureClippingType type)
Sets the feature clipping type to apply when clipping to the associated item.
bool isActive() const
Returns true if the item clipping is enabled and set to a valid source item.
An item which is drawn inside a QgsLayoutItemMap, e.g., a grid or map overview.
@ StackAboveMapLabels
Render above all map layers and labels.
StackingPosition stackingPosition() const
Returns the item's stacking position, which specifies where the in the map's stack the item should be...
bool enabled() const
Returns whether the item will be drawn.
An individual overview which is drawn above the map content in a QgsLayoutItemMap,...
Layout graphical items for displaying a map.
void setFollowVisibilityPreset(bool follow)
Sets whether the map should follow a map theme.
bool nextExportPart() override
Moves to the next export part for a multi-layered export item, during a multi-layered export.
void removeRenderedFeatureHandler(QgsRenderedFeatureHandlerInterface *handler)
Removes a previously added rendered feature handler.
void extentChanged()
Emitted when the map's extent changes.
QPointF mapToItemCoords(QPointF mapCoords) const
Transforms map coordinates to item coordinates (considering rotation and move offset)
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified style entity visitor, causing it to visit all style entities associated with th...
~QgsLayoutItemMap() override
QIcon icon() const override
Returns the item's icon.
void preparedForAtlas()
Emitted when the map has been prepared for atlas rendering, just before actual rendering.
void setFollowVisibilityPresetName(const QString &name)
Sets preset name for map rendering.
QTransform layoutToMapCoordsTransform() const
Creates a transform from layout coordinates to map coordinates.
bool writePropertiesToElement(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const override
Stores item state within an XML DOM element.
QgsMapSettings mapSettings(const QgsRectangle &extent, QSizeF size, double dpi, bool includeLayerSettings) const
Returns map settings that will be used for drawing of the map.
bool isLabelBlockingItem(QgsLayoutItem *item) const
Returns true if the specified item is a "label blocking item".
void storeCurrentLayerStyles()
Stores the current project layer styles into style overrides.
void setAtlasDriven(bool enabled)
Sets whether the map extent will follow the current atlas feature.
QgsLayoutMeasurement labelMargin() const
Returns the margin from the map edges in which no labels may be placed.
AtlasScalingMode
Scaling modes used for the serial rendering (atlas)
@ Predefined
A scale is chosen from the predefined scales.
@ Auto
The extent is adjusted so that each feature is fully visible.
@ Fixed
The current scale of the map is used for each feature of the atlas.
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...
Q_DECL_DEPRECATED int numberExportLayers() const override
Returns the number of layers that this item requires for exporting during layered exports (e....
void layerStyleOverridesChanged()
Emitted when layer style overrides are changed... a means to let associated legend items know they sh...
void updateBoundingRect()
Updates the bounding rect of this item. Call this function before doing any changes related to annota...
void moveContent(double dx, double dy) override
Moves the content of the item, by a specified dx and dy in layout units.
QgsLayoutItemMapGrid * grid()
Returns the map item's first grid.
void mapRotationChanged(double newRotation)
Emitted when the map's rotation changes.
int type() const override
void previewRefreshed()
Emitted whenever the item's map preview has been refreshed.
friend class QgsLayoutItemMapOverview
void setExtent(const QgsRectangle &extent)
Sets a new extent for the map.
void paint(QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget) override
void draw(QgsLayoutItemRenderContext &context) override
Draws the item's contents using the specified item render context.
QPolygonF visibleExtentPolygon() const
Returns a polygon representing the current visible map extent, considering map extents and rotation.
QgsRectangle requestedExtent() const
Calculates the extent to request and the yShift of the top-left point in case of rotation.
QgsLayoutItemMap(QgsLayout *layout)
Constructor for QgsLayoutItemMap, with the specified parent layout.
void setMapFlags(QgsLayoutItemMap::MapItemFlags flags)
Sets the map item's flags, which control how the map content is drawn.
void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties) override
void zoomContent(double factor, QPointF point) override
Zooms content of item.
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...
void crsChanged()
Emitted when the map's coordinate reference system is changed.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the stored layers set.
QPolygonF transformedMapPolygon() const
Returns extent that considers rotation and shift with mOffsetX / mOffsetY.
static QgsLayoutItemMap * create(QgsLayout *layout)
Returns a new map item for the specified layout.
QRectF boundingRect() const override
QString displayName() const override
Gets item display name.
bool atlasDriven() const
Returns whether the map extent is set to follow the current atlas feature.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the stored overrides of styles for layers.
void stopLayeredExport() override
Stops a multi-layer export operation.
void addRenderedFeatureHandler(QgsRenderedFeatureHandlerInterface *handler)
Adds a rendered feature handler to use while rendering the map.
QPainterPath framePath() const override
Returns the path to use when drawing the item's frame or background.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
void startLayeredExport() override
Starts a multi-layer export operation.
bool containsWmsLayer() const
Returns true if the map contains a WMS layer.
void setScale(double scale, bool forceUpdate=true)
Sets new map scale and changes only the map extent.
double mapRotation(QgsLayoutObject::PropertyValueType valueType=QgsLayoutObject::EvaluatedValue) const
Returns the rotation used for drawing the map within the layout item, in degrees clockwise.
double mapUnitsToLayoutUnits() const
Returns the conversion factor from map units to layout units.
QgsLayoutItemMap::MapItemFlags mapFlags() const
Returns the map item's flags, which control how the map content is drawn.
void setLabelMargin(const QgsLayoutMeasurement &margin)
Sets the margin from the map edges in which no labels may be placed.
void themeChanged(const QString &theme)
Emitted when the map's associated theme is changed.
QgsLayoutItem::ExportLayerDetail exportLayerDetails() const override
Returns the details for the specified current export layer.
void zoomToExtent(const QgsRectangle &extent)
Zooms the map so that the specified extent is fully visible within the map item.
double scale() const
Returns the map scale.
@ ShowPartialLabels
Whether to draw labels which are partially outside of the map view.
@ ShowUnplacedLabels
Whether to render unplaced labels in the map view.
bool drawAnnotations() const
Returns whether annotations are drawn within the map.
void removeLabelBlockingItem(QgsLayoutItem *item)
Removes the specified layout item from the map's "label blocking items".
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the map's preset crs (coordinate reference system).
void invalidateCache() override
QgsRectangle extent() const
Returns the current map extent.
QgsLayoutItemMapOverview * overview()
Returns the map item's first overview.
void finalizeRestoreFromXml() override
Called after all pending items have been restored from XML.
bool readPropertiesFromElement(const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context) override
Sets item state from a DOM element.
void setFrameStrokeWidth(QgsLayoutMeasurement width) override
Sets the frame stroke width.
bool containsAdvancedEffects() const override
Returns true if the item contains contents with blend modes or transparency effects which can only be...
friend class QgsLayoutItemMapGrid
QgsLayoutItem::Flags itemFlags() const override
Returns the item's flags, which indicate how the item behaves.
QList< QgsMapLayer * > layers() const
Returns the stored layer set.
void setMoveContentPreviewOffset(double dx, double dy) override
Sets temporary offset for the item, by a specified dx and dy in layout units.
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...
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
double atlasMargin(QgsLayoutObject::PropertyValueType valueType=QgsLayoutObject::EvaluatedValue)
Returns the margin size (percentage) used when the map is in atlas mode.
void addLabelBlockingItem(QgsLayoutItem *item)
Sets the specified layout item as a "label blocking item" for this map.
void assignFreeId()
Sets the map id() to a number not yet used in the layout.
ExportLayerBehavior exportLayerBehavior() const override
Returns the behavior of this item during exporting to layered exports (e.g.
QgsLabelingResults * previewLabelingResults() const
Returns the labeling results of the most recent preview map render.
Contains settings and helpers relating to a render of a QgsLayoutItem.
Base class for graphical items within a QgsLayout.
virtual void drawFrame(QgsRenderContext &context)
Draws the frame around the item.
virtual QPainterPath framePath() const
Returns the path to use when drawing the item's frame or background.
virtual void setFrameStrokeWidth(QgsLayoutMeasurement width)
Sets the frame stroke width.
void rotationChanged(double newRotation)
Emitted on item rotation change.
QColor backgroundColor() const
Returns the background color for this item.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
virtual void drawBackground(QgsRenderContext &context)
Draws the background for the item.
virtual bool requiresRasterization() const
Returns true if the item is drawn in such a way that forces the whole layout to be rasterized when ex...
bool shouldDrawItem() const
Returns whether the item should be drawn in the current context.
virtual void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties)
Refreshes a data defined property for the item by reevaluating the property's value and redrawing the...
@ FlagOverridesPaint
Item overrides the default layout item painting method.
virtual bool containsAdvancedEffects() const
Returns true if the item contains contents with blend modes or transparency effects which can only be...
void sizePositionChanged()
Emitted when the item's size or position changes.
virtual QString uuid() const
Returns the item identification string.
QString id() const
Returns the item's ID name.
bool frameEnabled() const
Returns true if the item includes a frame.
ExportLayerBehavior
Behavior of item when exporting to layered outputs.
@ ItemContainsSubLayers
Item contains multiple sublayers which must be individually exported.
void clipPathChanged()
Emitted when the item's clipping path has changed.
bool hasBackground() const
Returns true if the item has a background.
void refresh() override
Refreshes the item, causing a recalculation of any property overrides and recalculation of its positi...
void attemptSetSceneRect(const QRectF &rect, bool includesFrame=false)
Attempts to update the item's position and size to match the passed rect in layout coordinates.
void backgroundTaskCountChanged(int count)
Emitted whenever the number of background tasks an item is executing changes.
This class provides a method of storing measurements for use in QGIS layouts using a variety of diffe...
void setLength(const double length)
Sets the length of the measurement.
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.
QgsUnitTypes::LayoutUnit units() const
Returns the units for the measurement.
void setUnits(const QgsUnitTypes::LayoutUnit units)
Sets the units for the measurement.
QgsPropertyCollection mDataDefinedProperties
const QgsLayout * layout() const
Returns the layout the object is attached to.
void changed()
Emitted when the object's properties change.
QPointer< QgsLayout > mLayout
DataDefinedProperty
Data defined properties for different item types.
@ MapYMin
Map extent y minimum.
@ MapStylePreset
Layer and style map theme.
@ MapXMax
Map extent x maximum.
@ StartDateTime
Temporal range's start DateTime.
@ AllProperties
All properties for item.
@ EndDateTime
Temporal range's end DateTime.
@ MapAtlasMargin
Map atlas margin.
@ MapYMax
Map extent y maximum.
@ MapXMin
Map extent x minimum.
@ MapLabelMargin
Map label margin.
@ MapLayers
Map layer set.
@ MapRotation
Map rotation.
PropertyValueType
Specifies whether the value returned by a function should be the original, user set value,...
@ EvaluatedValue
Return the current evaluated value for the property.
void predefinedScalesChanged()
Emitted when the list of predefined scales changes.
@ FlagRenderLabelsByMapLayer
When rendering map items to multi-layered exports, render labels belonging to different layers into s...
@ FlagUseAdvancedEffects
Enable advanced effects such as blend modes.
@ FlagDrawSelection
Draw selection.
@ 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...
@ FlagHideCoverageLayer
Hide coverage layer in outputs.
@ FlagDisableTiledRasterLayerRenders
If set, then raster layers will not be drawn as separate tiles. This may improve the appearance in ex...
static QgsRenderContext createRenderContextForMap(QgsLayoutItemMap *map, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout map and painter destination.
static void rotate(double angle, double &x, double &y)
Rotates a point / vector around the origin.
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.
QgsLayoutItem * itemByUuid(const QString &uuid, bool includeTemplateUuids=false) const
Returns the layout item with matching uuid unique identifier, or nullptr if a matching item could not...
void refreshed()
Emitted when the layout has been refreshed and items should also be refreshed and updated.
QgsProject * project() const
The project associated with the layout.
A map clipping region (in map coordinates and CRS).
void setRestrictToLayers(bool enabled)
Sets whether clipping should be restricted to a subset of layers.
FeatureClippingType
Feature clipping behavior, which controls how features from vector layers will be clipped.
void setFeatureClip(FeatureClippingType type)
Sets the feature clipping type.
void setRestrictedLayers(const QList< QgsMapLayer * > &layers)
Sets a list of layers to restrict the clipping region effects to.
Stores style information (renderer, opacity, labeling, diagrams etc.) applicable to a map layer.
void readXml(const QDomElement &styleElement)
Read style configuration (for project file reading)
void readFromLayer(QgsMapLayer *layer)
Store layer's active style information in the instance.
void writeXml(QDomElement &styleElement) const
Write style configuration (for project file writing)
QString xmlData() const
Returns XML content of the style.
Base class for all map layer types.
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
Job implementation that renders everything sequentially using a custom painter.
void cancelWithoutBlocking() override
Triggers cancellation of the rendering job without blocking.
void finished()
emitted when asynchronous rendering is finished (or canceled).
@ RenderLabelsByMapLayer
Labels should be rendered in individual stages by map layer. This allows separation of labels belongi...
@ Finished
Rendering is finished.
@ Symbology
Rendering layer symbology.
@ Labels
Rendering labels.
static QStringList containsAdvancedEffects(const QgsMapSettings &mapSettings, EffectsCheckFlags flags=QgsMapSettingsUtils::EffectsCheckFlags())
Checks whether any of the layers attached to a map settings object contain advanced effects.
The QgsMapSettings class contains configuration for rendering of the map.
void addClippingRegion(const QgsMapClippingRegion ®ion)
Adds a new clipping region to the map settings.
QList< QgsMapLayer * > layers(bool expandGroupLayers=false) const
Returns the list of layers which will be rendered in the map.
void setSelectionColor(const QColor &color)
Sets the color that is used for drawing of selected vector features.
void setSimplifyMethod(const QgsVectorSimplifyMethod &method)
Sets the simplification setting to use when rendering vector layers.
QPolygonF visiblePolygon() const
Returns the visible area as a polygon (may be rotated)
void addRenderedFeatureHandler(QgsRenderedFeatureHandlerInterface *handler)
Adds a rendered feature handler to use while rendering the map settings.
void setTextRenderFormat(Qgis::TextRenderFormat format)
Sets the text render format, which dictates how text is rendered (e.g.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the list of layers to render in the map.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
void setDpiTarget(double dpi)
Sets the target dpi (dots per inch) to be taken into consideration when rendering.
long long currentFrame() const
Returns the current frame number of the map, for maps which are part of an animation.
void setOutputDpi(double dpi)
Sets the dpi (dots per inch) used for conversion between real world units (e.g.
void setRendererUsage(Qgis::RendererUsage rendererUsage)
Sets the rendering usage.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the map of map layer style overrides (key: layer ID, value: style name) where a different style ...
void setExtent(const QgsRectangle &rect, bool magnified=true)
Sets the coordinates of the rectangle which should be rendered.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
double frameRate() const
Returns the frame rate of the map (in frames per second), for maps which are part of an animation.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets the global configuration of the labeling engine.
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the coordinate transform context, which stores various information regarding which datum transfo...
void setRotation(double rotation)
Sets the rotation of the resulting map image, in degrees clockwise.
void setPathResolver(const QgsPathResolver &resolver)
Sets the path resolver for conversion between relative and absolute paths during rendering operations...
void setLabelBoundaryGeometry(const QgsGeometry &boundary)
Sets the label boundary geometry, which restricts where in the rendered map labels are permitted to b...
void setLabelBlockingRegions(const QList< QgsLabelBlockingRegion > ®ions)
Sets a list of regions to avoid placing labels within.
void setOutputSize(QSize size)
Sets the size of the resulting map image, in pixels.
void setBackgroundColor(const QColor &color)
Sets the background color of the map.
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
void setFlag(Qgis::MapSettingsFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected)
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Sets the destination crs (coordinate reference system) for the map render.
void mapThemeRenamed(const QString &name, const QString &newName)
Emitted when a map theme within the collection is renamed.
void mapThemeChanged(const QString &theme)
Emitted when a map theme changes definition.
A class to represent a 2D point.
QString description() const
Description.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
void layersWillBeRemoved(const QStringList &layerIds)
Emitted when one or more layers are about to be removed from the registry.
void crsChanged()
Emitted when the CRS of the project has changed.
QgsMapThemeCollection * mapThemeCollection
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
QgsLayerTree * layerTreeRoot() const
Returns pointer to the root (invisible) node of the project's layer tree.
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
void setYMinimum(double y) SIP_HOLDGIL
Set the minimum y value.
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
void setXMaximum(double x) SIP_HOLDGIL
Set the maximum x value.
void setXMinimum(double x) SIP_HOLDGIL
Set the minimum x value.
double height() const SIP_HOLDGIL
Returns the height of the rectangle.
void setYMaximum(double y) SIP_HOLDGIL
Set the maximum y value.
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
static QgsRectangle fromCenterAndSize(const QgsPointXY ¢er, double width, double height)
Creates a new rectangle, given the specified center point and width and height.
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
Contains information about the context of a rendering operation.
void setForceVectorOutput(bool force)
Sets whether rendering operations should use vector operations instead of any faster raster shortcuts...
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 ...
QgsExpressionContext & expressionContext()
Gets the expression context.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
An interface for classes which provider custom handlers for features rendered as part of a map render...
Calculates scale for a given combination of canvas size, map extent, and monitor dpi.
double calculate(const QgsRectangle &mapExtent, double canvasWidth) const
Calculate the scale denominator.
void setDpi(double dpi)
Sets the dpi (dots per inch) for the output resolution, to be used in scale calculations.
void setMapUnits(QgsUnitTypes::DistanceUnit mapUnits)
Set the map units.
Scoped object for saving and restoring a QPainter object's state.
An interface for classes which can visit style entity (e.g.
@ LayoutItem
Individual item in a print layout.
virtual bool visitExit(const QgsStyleEntityVisitorInterface::Node &node)
Called when the visitor stops visiting a node.
virtual bool visitEnter(const QgsStyleEntityVisitorInterface::Node &node)
Called when the visitor starts visiting a node.
const QgsDateTimeRange & temporalRange() const
Returns the datetime range for the object.
bool isTemporal() const
Returns true if the object's temporal range is enabled, and the object will be filtered when renderin...
void setIsTemporal(bool enabled)
Sets whether the temporal range is enabled (i.e.
void setTemporalRange(const QgsDateTimeRange &range)
Sets the temporal range for the object.
@ LayoutMillimeters
Millimeters.
static Q_INVOKABLE QString toString(QgsUnitTypes::DistanceUnit unit)
Returns a translated string representing a distance unit.
@ NoSimplification
No simplification can be applied.
static double scaleToZoom(double mapScale, double z0Scale=559082264.0287178)
Finds zoom level given map scale denominator.
static int scaleToZoomLevel(double mapScale, int sourceMinZoom, int sourceMaxZoom, double z0Scale=559082264.0287178)
Finds the best fitting zoom level given a map scale denominator and allowed zoom level range.
static GeometryType geometryType(Type type) SIP_HOLDGIL
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
#define Q_NOWARN_DEPRECATED_POP
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
#define Q_NOWARN_DEPRECATED_PUSH
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
const QgsCoordinateReferenceSystem & crs
Single variable definition for use within a QgsExpressionContextScope.
Contains details of a particular export layer relating to a layout item.
QPainter::CompositionMode compositionMode
Associated composition mode if this layer is associated with a map layer.
QString mapLayerId
Associated map layer ID, or an empty string if this export layer is not associated with a map layer.
double opacity
Associated opacity, if this layer is associated with a map layer.
QString name
User-friendly name for the export layer.
QString mapTheme
Associated map theme, or an empty string if this export layer does not need to be associated with a m...
Contains information relating to a node (i.e.
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.
QString source
Weak reference to layer public source.
QString name
Weak reference to layer name.
QString provider
Weak reference to layer provider.
TYPE * resolve(const QgsProject *project)
Resolves the map layer by attempting to find a layer with matching ID within a project.
QString layerId
Original layer ID.