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 if ( mOverviewStack->hasEnabledItems() )
1064 mCurrentExportPart = OverviewMapExtent;
1069 case OverviewMapExtent:
1072 mCurrentExportPart = Frame;
1079 if ( isSelected() && !
mLayout->renderContext().isPreviewRender() )
1081 mCurrentExportPart = SelectionBoxes;
1086 case SelectionBoxes:
1087 mCurrentExportPart = End;
1108 switch ( mCurrentExportPart )
1118 if ( !mExportThemes.empty() && mExportThemeIt != mExportThemes.end() )
1121 if ( mStagedRendererJob )
1123 switch ( mStagedRendererJob->currentStage() )
1127 detail.
mapLayerId = mStagedRendererJob->currentLayerId();
1133 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), layer->name() );
1139 detail.
mapLayerId = mStagedRendererJob->currentLayerId();
1145 detail.
name = tr(
"%1: %2 (Labels)" ).arg(
displayName(), layer->name() );
1164 if ( !layers.isEmpty() )
1180 case OverviewMapExtent:
1188 case SelectionBoxes:
1203 void QgsLayoutItemMap::drawMap( QPainter *painter,
const QgsRectangle &
extent, QSizeF size,
double dpi )
1217 if ( shouldDrawPart( OverviewMapExtent ) )
1228 mRenderingErrors = job.
errors();
1231 void QgsLayoutItemMap::recreateCachedImageInBackground()
1237 QPainter *oldPainter = mPainter.release();
1238 QImage *oldImage = mCacheRenderingImage.release();
1241 oldJob->deleteLater();
1245 oldJob->cancelWithoutBlocking();
1249 mCacheRenderingImage.reset(
nullptr );
1253 Q_ASSERT( !mPainterJob );
1254 Q_ASSERT( !mPainter );
1255 Q_ASSERT( !mCacheRenderingImage );
1261 int w =
static_cast< int >( std::round( widthLayoutUnits * mPreviewScaleFactor ) );
1262 int h =
static_cast< int >( std::round( heightLayoutUnits * mPreviewScaleFactor ) );
1265 if ( w > 5000 || h > 5000 )
1270 h =
static_cast< int>( std::round( w * heightLayoutUnits / widthLayoutUnits ) );
1275 w =
static_cast< int >( std::round( h * widthLayoutUnits / heightLayoutUnits ) );
1279 if ( w <= 0 || h <= 0 )
1282 mCacheRenderingImage.reset(
new QImage( w, h, QImage::Format_ARGB32 ) );
1285 mCacheRenderingImage->setDotsPerMeterX( static_cast< int >( std::round( 1000 * w / widthLayoutUnits ) ) );
1286 mCacheRenderingImage->setDotsPerMeterY( static_cast< int >( std::round( 1000 * h / heightLayoutUnits ) ) );
1297 mCacheRenderingImage->fill( QColor( 255, 255, 255, 0 ).rgba() );
1300 mCacheInvalidated =
false;
1301 mPainter.reset(
new QPainter( mCacheRenderingImage.get() ) );
1304 if ( shouldDrawPart( OverviewMapExtent ) )
1306 settings.
setLayers( mOverviewStack->modifyMapLayerList( settings.
layers() ) );
1311 mPainterJob->start();
1323 mDrawingPreview =
false;
1347 jobMapSettings.
setRotation( mEvaluatedMapRotation );
1351 if ( includeLayerSettings )
1359 if ( !
mLayout->renderContext().isPreviewRender() )
1394 if ( mEvaluatedLabelMargin.
length() > 0 )
1397 visiblePoly.append( visiblePoly.at( 0 ) );
1398 const double layoutLabelMargin =
mLayout->convertToLayoutUnits( mEvaluatedLabelMargin );
1399 const double layoutLabelMarginInMapUnits = layoutLabelMargin / rect().width() * jobMapSettings.
extent().
width();
1401 mapBoundaryGeom = mapBoundaryGeom.
buffer( -layoutLabelMarginInMapUnits, 0 );
1405 if ( !mBlockingLabelItems.isEmpty() )
1415 return jobMapSettings;
1422 mBlockingLabelItems.clear();
1423 for (
const QString &
uuid : qgis::as_const( mBlockingLabelItemUuids ) )
1432 mOverviewStack->finalizeRestoreFromXml();
1433 mGridStack->finalizeRestoreFromXml();
1444 return mCurrentRectangle;
1477 QVariantList layersIds;
1487 const QList<QgsMapLayer *> layersInMap =
layersToRender( &context );
1489 layersIds.reserve( layersInMap.count() );
1490 layers.reserve( layersInMap.count() );
1493 layersIds << layer->id();
1499 scope->
addFunction( QStringLiteral(
"is_layer_visible" ),
new QgsExpressionContextUtils::GetLayerVisibility( layersInMap,
scale() ) );
1507 if ( extentWidth <= 0 )
1511 return rect().width() / extentWidth;
1516 double dx = mXOffset;
1517 double dy = mYOffset;
1518 transformShift( dx, dy );
1520 poly.translate( -dx, -dy );
1526 if ( !mBlockingLabelItems.contains( item ) )
1527 mBlockingLabelItems.append( item );
1534 mBlockingLabelItems.removeAll( item );
1541 return mBlockingLabelItems.contains( item );
1550 if ( mOverviewStack )
1552 for (
int i = 0; i < mOverviewStack->size(); ++i )
1554 if ( mOverviewStack->item( i )->accept( visitor ) )
1561 for (
int i = 0; i < mGridStack->size(); ++i )
1563 if ( mGridStack->item( i )->accept( visitor ) )
1576 mRenderedFeatureHandlers.append( handler );
1581 mRenderedFeatureHandlers.removeAll( handler );
1587 if ( mapPoly.empty() )
1589 return QPointF( 0, 0 );
1594 double dx = mapCoords.x() - rotationPoint.
x();
1595 double dy = mapCoords.y() - rotationPoint.
y();
1597 QgsPointXY backRotatedCoords( rotationPoint.
x() + dx, rotationPoint.
y() + dy );
1600 double xItem = rect().width() * ( backRotatedCoords.x() - unrotatedExtent.xMinimum() ) / unrotatedExtent.width();
1601 double yItem = rect().height() * ( 1 - ( backRotatedCoords.y() - unrotatedExtent.yMinimum() ) / unrotatedExtent.height() );
1602 return QPointF( xItem, yItem );
1616 mapPolygon( newExtent, poly );
1617 QRectF bRect = poly.boundingRect();
1631 mCacheInvalidated =
true;
1637 QRectF rectangle = rect();
1638 double frameExtension =
frameEnabled() ? pen().widthF() / 2.0 : 0.0;
1640 double topExtension = 0.0;
1641 double rightExtension = 0.0;
1642 double bottomExtension = 0.0;
1643 double leftExtension = 0.0;
1646 mGridStack->calculateMaxGridExtension( topExtension, rightExtension, bottomExtension, leftExtension );
1648 topExtension = std::max( topExtension, frameExtension );
1649 rightExtension = std::max( rightExtension, frameExtension );
1650 bottomExtension = std::max( bottomExtension, frameExtension );
1651 leftExtension = std::max( leftExtension, frameExtension );
1653 rectangle.setLeft( rectangle.left() - leftExtension );
1654 rectangle.setRight( rectangle.right() + rightExtension );
1655 rectangle.setTop( rectangle.top() - topExtension );
1656 rectangle.setBottom( rectangle.bottom() + bottomExtension );
1657 if ( rectangle != mCurrentRectangle )
1659 prepareGeometryChange();
1660 mCurrentRectangle = rectangle;
1676 refreshMapExtents( &context );
1678 if ( mExtent != beforeExtent )
1685 refreshLabelMargin(
false );
1689 mCacheInvalidated =
true;
1694 void QgsLayoutItemMap::layersAboutToBeRemoved(
const QList<QgsMapLayer *> &
layers )
1696 if ( !mLayers.isEmpty() || mLayerStyleOverrides.isEmpty() )
1700 mLayerStyleOverrides.remove( layer->id() );
1702 _qgis_removeLayers( mLayers, layers );
1706 void QgsLayoutItemMap::painterJobFinished()
1709 mPainterJob.reset(
nullptr );
1710 mPainter.reset(
nullptr );
1711 mCacheFinalImage = std::move( mCacheRenderingImage );
1712 mLastRenderedImageOffsetX = 0;
1713 mLastRenderedImageOffsetY = 0;
1718 void QgsLayoutItemMap::shapeChanged()
1723 double w = rect().width();
1724 double h = rect().height();
1727 double newWidth = mExtent.
width();
1729 double newHeight = newWidth * h / w;
1734 refreshMapExtents();
1741 void QgsLayoutItemMap::mapThemeChanged(
const QString &theme )
1743 if ( theme == mCachedLayerStyleOverridesPresetName )
1744 mCachedLayerStyleOverridesPresetName.clear();
1747 void QgsLayoutItemMap::connectUpdateSlot()
1755 this, &QgsLayoutItemMap::layersAboutToBeRemoved );
1759 if (
layers().isEmpty() )
1785 updateAtlasFeature();
1794 QTransform mapTransform;
1795 QPolygonF thisRectPoly = QPolygonF( QRectF( 0, 0, rect().width(), rect().height() ) );
1797 thisRectPoly.pop_back();
1798 thisExtent.pop_back();
1800 QPolygonF thisItemPolyInLayout = mapToScene( thisRectPoly );
1803 QTransform::quadToQuad( thisItemPolyInLayout, thisExtent, mapTransform );
1804 return mapTransform;
1807 QList<QgsLabelBlockingRegion> QgsLayoutItemMap::createLabelBlockingRegions(
const QgsMapSettings & )
const 1810 QList< QgsLabelBlockingRegion > blockers;
1811 blockers.reserve( mBlockingLabelItems.count() );
1812 for (
const auto &item : qgis::as_const( mBlockingLabelItems ) )
1819 if ( item->property(
"wasVisible" ).isValid() )
1821 if ( !item->property(
"wasVisible" ).toBool() )
1824 else if ( !item->isVisible() )
1827 QPolygonF itemRectInMapCoordinates = mapTransform.map( item->mapToScene( item->rect() ) );
1828 itemRectInMapCoordinates.append( itemRectInMapCoordinates.at( 0 ) );
1837 return mLabelMargin;
1842 mLabelMargin = margin;
1843 refreshLabelMargin(
false );
1846 void QgsLayoutItemMap::updateToolTip()
1855 if ( mFollowVisibilityPreset )
1857 presetName = mFollowVisibilityPresetName;
1861 else if ( !mExportThemes.empty() && mExportThemeIt != mExportThemes.end() )
1862 presetName = *mExportThemeIt;
1873 QList<QgsMapLayer *> renderLayers;
1875 QString presetName = themeToRender( *evalContext );
1876 if ( !presetName.isEmpty() )
1878 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
1879 renderLayers =
mLayout->project()->mapThemeCollection()->mapThemeVisibleLayers( presetName );
1881 renderLayers =
mLayout->project()->mapThemeCollection()->masterVisibleLayers();
1883 else if ( !
layers().isEmpty() )
1889 renderLayers =
mLayout->project()->mapThemeCollection()->masterVisibleLayers();
1896 renderLayers.clear();
1898 const QStringList layerNames = ddLayers.split(
'|' );
1900 for (
const QString &name : layerNames )
1902 const QList< QgsMapLayer * > matchingLayers =
mLayout->project()->mapLayersByName( name );
1905 renderLayers << layer;
1914 int removeAt = renderLayers.indexOf(
mLayout->reportContext().layer() );
1915 if ( removeAt != -1 )
1917 renderLayers.removeAt( removeAt );
1922 renderLayers.erase( std::remove_if( renderLayers.begin(), renderLayers.end(), [](
QgsMapLayer * layer )
1924 return !layer || !layer->isValid();
1925 } ), renderLayers.end() );
1927 return renderLayers;
1930 QMap<QString, QString> QgsLayoutItemMap::layerStyleOverridesToRender(
const QgsExpressionContext &context )
const 1932 QString presetName = themeToRender( context );
1933 if ( !presetName.isEmpty() )
1935 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
1937 if ( presetName != mCachedLayerStyleOverridesPresetName )
1940 mCachedPresetLayerStyleOverrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( presetName );
1941 mCachedLayerStyleOverridesPresetName = presetName;
1944 return mCachedPresetLayerStyleOverrides;
1947 return QMap<QString, QString>();
1949 else if ( mFollowVisibilityPreset )
1951 QString presetName = mFollowVisibilityPresetName;
1954 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
1956 if ( presetName.isEmpty() || presetName != mCachedLayerStyleOverridesPresetName )
1959 mCachedPresetLayerStyleOverrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( presetName );
1960 mCachedLayerStyleOverridesPresetName = presetName;
1963 return mCachedPresetLayerStyleOverrides;
1966 return QMap<QString, QString>();
1968 else if ( mKeepLayerStyles )
1970 return mLayerStyleOverrides;
1974 return QMap<QString, QString>();
1978 QgsRectangle QgsLayoutItemMap::transformedExtent()
const 1980 double dx = mXOffset;
1981 double dy = mYOffset;
1982 transformShift( dx, dy );
1986 void QgsLayoutItemMap::mapPolygon(
const QgsRectangle &extent, QPolygonF &poly )
const 1996 poly << QPointF( poly.at( 0 ) );
2005 dx = rotationPoint.
x() - extent.
xMinimum();
2006 dy = rotationPoint.
y() - extent.
yMaximum();
2008 poly << QPointF( rotationPoint.
x() - dx, rotationPoint.
y() - dy );
2011 dx = rotationPoint.
x() - extent.
xMaximum();
2012 dy = rotationPoint.
y() - extent.
yMaximum();
2014 poly << QPointF( rotationPoint.
x() - dx, rotationPoint.
y() - dy );
2017 dx = rotationPoint.
x() - extent.
xMaximum();
2018 dy = rotationPoint.
y() - extent.
yMinimum();
2020 poly << QPointF( rotationPoint.
x() - dx, rotationPoint.
y() - dy );
2023 dx = rotationPoint.
x() - extent.
xMinimum();
2024 dy = rotationPoint.
y() - extent.
yMinimum();
2026 poly << QPointF( rotationPoint.
x() - dx, rotationPoint.
y() - dy );
2029 poly << QPointF( poly.at( 0 ) );
2032 void QgsLayoutItemMap::transformShift(
double &xShift,
double &yShift )
const 2035 double dxScaled = xShift * mmToMapUnits;
2036 double dyScaled = - yShift * mmToMapUnits;
2051 const QList< QgsAnnotation * > annotations =
mLayout->project()->annotationManager()->annotations();
2052 if ( annotations.isEmpty() )
2062 if ( !annotation || !annotation->isVisible() )
2066 if ( annotation->mapLayer() && !layers.contains( annotation->mapLayer() ) )
2069 drawAnnotation( annotation, rc );
2083 double itemX, itemY;
2086 QPointF mapPos = layoutMapPosForItem( annotation );
2095 context.
painter()->translate( itemX, itemY );
2098 double dotsPerMM = context.
painter()->device()->logicalDpiX() / 25.4;
2099 context.
painter()->scale( 1 / dotsPerMM, 1 / dotsPerMM );
2101 annotation->
render( context );
2105 QPointF QgsLayoutItemMap::layoutMapPosForItem(
const QgsAnnotation *annotation )
const 2108 return QPointF( 0, 0 );
2117 if ( annotationCrs !=
crs() )
2134 void QgsLayoutItemMap::drawMapFrame( QPainter *p )
2140 p->setBrush( Qt::NoBrush );
2141 p->setRenderHint( QPainter::Antialiasing,
true );
2142 p->drawRect( QRectF( 0, 0, rect().width(), rect().height() ) );
2147 void QgsLayoutItemMap::drawMapBackground( QPainter *p )
2152 p->setBrush( brush() );
2153 p->setPen( Qt::NoPen );
2154 p->setRenderHint( QPainter::Antialiasing,
true );
2155 p->drawRect( QRectF( 0, 0, rect().width(), rect().height() ) );
2160 bool QgsLayoutItemMap::shouldDrawPart( QgsLayoutItemMap::PartType part )
const 2162 if ( mCurrentExportPart == NotLayered )
2180 return mCurrentExportPart == Layer;
2183 return mCurrentExportPart == Grid && mGridStack->hasEnabledItems();
2185 case OverviewMapExtent:
2186 return mCurrentExportPart == OverviewMapExtent && mOverviewStack->hasEnabledItems();
2191 case SelectionBoxes:
2192 return mCurrentExportPart == SelectionBoxes && isSelected();
2210 bool useDdXMin =
false;
2211 bool useDdXMax =
false;
2212 bool useDdYMin =
false;
2213 bool useDdYMax =
false;
2245 if ( newExtent != mExtent )
2251 double currentWidthHeightRatio = mExtent.
width() / mExtent.
height();
2252 double newWidthHeightRatio = newExtent.
width() / newExtent.
height();
2254 if ( currentWidthHeightRatio < newWidthHeightRatio )
2257 double newHeight = newExtent.
width() / currentWidthHeightRatio;
2258 double deltaHeight = newHeight - newExtent.
height();
2265 double newWidth = currentWidthHeightRatio * newExtent.
height();
2266 double deltaWidth = newWidth - newExtent.
width();
2271 mExtent = newExtent;
2281 newExtent = mExtent;
2284 if ( useDdXMax || useDdXMin || useDdYMax || useDdYMin )
2288 if ( useDdXMin && !useDdXMax )
2294 else if ( !useDdXMin && useDdXMax )
2300 if ( useDdYMin && !useDdYMax )
2306 else if ( !useDdYMin && useDdYMax )
2313 if ( newExtent != mExtent )
2315 mExtent = newExtent;
2332 void QgsLayoutItemMap::refreshLabelMargin(
bool updateItem )
2336 mEvaluatedLabelMargin.
setLength( labelMargin );
2345 void QgsLayoutItemMap::updateAtlasFeature()
2364 if ( mAtlasScalingMode ==
Fixed || mAtlasScalingMode ==
Predefined || isPointLayer )
2369 double originalScale = calc.
calculate( originalExtent, rect().width() );
2370 double geomCenterX = ( xa1 + xa2 ) / 2.0;
2371 double geomCenterY = ( ya1 + ya2 ) / 2.0;
2372 QVector<qreal> scales;
2374 if ( !
mLayout->reportContext().predefinedScales().empty() )
2375 scales =
mLayout->reportContext().predefinedScales();
2377 scales =
mLayout->renderContext().predefinedScales();
2379 if ( mAtlasScalingMode ==
Fixed || isPointLayer || scales.isEmpty() )
2382 double xMin = geomCenterX - originalExtent.
width() / 2.0;
2383 double yMin = geomCenterY - originalExtent.
height() / 2.0;
2386 xMin + originalExtent.
width(),
2387 yMin + originalExtent.
height() );
2391 double newScale = calc.
calculate( newExtent, rect().width() );
2392 newExtent.
scale( originalScale / newScale );
2397 double newWidth = originalExtent.
width();
2398 double newHeight = originalExtent.
height();
2399 for (
int i = 0; i < scales.size(); i++ )
2401 double ratio = scales[i] / originalScale;
2402 newWidth = originalExtent.
width() * ratio;
2403 newHeight = originalExtent.
height() * ratio;
2406 double xMin = geomCenterX - newWidth / 2.0;
2407 double yMin = geomCenterY - newHeight / 2.0;
2415 double newScale = calc.
calculate( newExtent, rect().width() );
2416 newExtent.
scale( scales[i] / newScale );
2426 else if ( mAtlasScalingMode ==
Auto )
2430 double geomRatio = bounds.
width() / bounds.
height();
2431 double mapRatio = originalExtent.
width() / originalExtent.
height();
2434 if ( geomRatio < mapRatio )
2437 double adjWidth = ( mapRatio * bounds.
height() - bounds.
width() ) / 2.0;
2442 else if ( geomRatio > mapRatio )
2445 double adjHeight = ( bounds.
width() / mapRatio - bounds.
height() ) / 2.0;
2451 const double evaluatedAtlasMargin =
atlasMargin();
2452 if ( evaluatedAtlasMargin > 0.0 )
2454 newExtent.
scale( 1 + evaluatedAtlasMargin );
2470 if ( mEvaluatedMapRotation != 0.0 )
2480 double dx = std::max( std::abs( prevCenter.
x() - bounds.
xMinimum() ),
2481 std::abs( prevCenter.
x() - bounds.
xMaximum() ) );
2482 double dy = std::max( std::abs( prevCenter.
y() - bounds.
yMinimum() ),
2483 std::abs( prevCenter.
y() - bounds.
yMaximum() ) );
2486 center.
x() + dx, center.
y() + dy );
2494 void QgsLayoutItemMap::createStagedRenderJob(
const QgsRectangle &extent,
const QSizeF size,
double dpi )
2497 mStagedRendererJob = qgis::make_unique< QgsMapRendererStagedRenderJob >(
mapSettings( extent, size, dpi,
true ),
2500 : QgsMapRendererStagedRenderJob::Flags(
nullptr ) );
2501 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.
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.
void setExtent(const QgsRectangle &extent)
Sets a new extent for the map.
void layerOrderChanged()
Emitted when the layer order has changed.
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...
TYPE * resolveWeakly(const QgsProject *project)
Resolves the map layer by attempting to find a matching layer in a project using a weak match...
void setOutputDpi(double dpi)
Sets DPI used for conversion between real world units (e.g. mm) and pixels.
#define Q_NOWARN_DEPRECATED_PUSH
QString toProj4() const
Returns a Proj4 string representation of this CRS.
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.
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...
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.
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.
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.