42 #include <QStyleOptionGraphicsItem>
50 mBackgroundUpdateTimer =
new QTimer(
this );
51 mBackgroundUpdateTimer->setSingleShot(
true );
52 connect( mBackgroundUpdateTimer, &QTimer::timeout,
this, &QgsLayoutItemMap::recreateCachedImageInBackground );
56 setCacheMode( QGraphicsItem::NoCache );
63 mGridStack = std::make_unique< QgsLayoutItemMapGridStack >(
this );
64 mOverviewStack = std::make_unique< QgsLayoutItemMapOverviewStack >(
this );
97 mPainterJob->cancel();
122 QList<QgsLayoutItemMap *> mapsList;
123 mLayout->layoutItems( mapsList );
132 if ( map->mMapId == mMapId )
135 maxId = std::max( maxId, map->mMapId );
140 mLayout->itemsModel()->updateItemDisplayName(
this );
152 return tr(
"Map %1" ).arg( mMapId );
164 mCachedLayerStyleOverridesPresetName.clear();
168 updateAtlasFeature();
173 if ( rect().isEmpty() )
178 calculator.
setDpi( 25.4 );
185 double currentScaleDenominator =
scale();
192 double scaleRatio = scaleDenominator / currentScaleDenominator;
193 mExtent.
scale( scaleRatio );
195 if ( mAtlasDriven && mAtlasScalingMode ==
Fixed )
202 calculator.
setDpi( 25.4 );
203 scaleRatio = scaleDenominator / calculator.
calculate( mExtent, rect().width() );
204 mExtent.
scale( scaleRatio );
228 QRectF currentRect = rect();
230 double newHeight = currentRect.width() * mExtent.
height() / mExtent.
width();
242 double currentWidthHeightRatio = 1.0;
243 if ( !currentExtent.
isNull() )
244 currentWidthHeightRatio = currentExtent.
width() / currentExtent.
height();
246 currentWidthHeightRatio = rect().width() / rect().height();
247 double newWidthHeightRatio = newExtent.
width() / newExtent.
height();
249 if ( currentWidthHeightRatio < newWidthHeightRatio )
252 double newHeight = newExtent.
width() / currentWidthHeightRatio;
253 double deltaHeight = newHeight - newExtent.
height();
260 double newWidth = currentWidthHeightRatio * newExtent.
height();
261 double deltaWidth = newWidth - newExtent.
width();
266 if ( mExtent == newExtent )
285 QPolygonF QgsLayoutItemMap::calculateVisibleExtentPolygon(
bool includeClipping )
const
288 mapPolygon( mExtent, poly );
290 if ( includeClipping && mItemClippingSettings->
isActive() )
304 return calculateVisibleExtentPolygon(
true );
312 return mLayout->project()->crs();
327 return _qgis_listRefToRaw( mLayers );
332 mLayers = _qgis_listRawToRef(
layers );
337 if ( overrides == mLayerStyleOverrides )
340 mLayerStyleOverrides = overrides;
347 mLayerStyleOverrides.clear();
354 mLayerStyleOverrides.insert( layer->id(), style.
xmlData() );
361 if ( mFollowVisibilityPreset == follow )
364 mFollowVisibilityPreset = follow;
366 if ( !mFollowVisibilityPresetName.isEmpty() )
367 emit
themeChanged( mFollowVisibilityPreset ? mFollowVisibilityPresetName : QString() );
372 if ( name == mFollowVisibilityPresetName )
375 mFollowVisibilityPresetName = name;
376 if ( mFollowVisibilityPreset )
382 mLastRenderedImageOffsetX -= dx;
383 mLastRenderedImageOffsetY -= dy;
386 transformShift( dx, dy );
410 double mapY = mExtent.
yMinimum() + ( 1 - ( point.y() / rect().height() ) ) * ( mExtent.
yMaximum() - mExtent.
yMinimum() );
416 centerX = mapX + ( centerX - mapX ) * ( 1.0 / factor );
417 centerY = mapY + ( centerY - mapY ) * ( 1.0 / factor );
419 double newIntervalX, newIntervalY;
436 if ( mAtlasDriven && mAtlasScalingMode ==
Fixed )
443 calculator.
setDpi( 25.4 );
444 double scaleRatio =
scale() / calculator.
calculate( mExtent, rect().width() );
445 mExtent.
scale( scaleRatio );
461 if ( layer->dataProvider() && layer->providerType() == QLatin1String(
"wms" ) )
495 if ( mOverviewStack->containsAdvancedEffects() )
501 if ( mGridStack->containsAdvancedEffects() )
513 mMapRotation = rotation;
514 mEvaluatedMapRotation = mMapRotation;
528 mAtlasDriven = enabled;
545 double margin = mAtlasMargin;
553 margin = ddMargin / 100;
565 if ( mGridStack->size() < 1 )
568 mGridStack->addGrid(
grid );
570 return mGridStack->grid( 0 );
575 if ( mOverviewStack->size() < 1 )
578 mOverviewStack->addOverview(
overview );
580 return mOverviewStack->overview( 0 );
591 mapElem.setAttribute( QStringLiteral(
"keepLayerSet" ), QStringLiteral(
"true" ) );
595 mapElem.setAttribute( QStringLiteral(
"keepLayerSet" ), QStringLiteral(
"false" ) );
598 if ( mDrawAnnotations )
600 mapElem.setAttribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"true" ) );
604 mapElem.setAttribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"false" ) );
608 QDomElement extentElem = doc.createElement( QStringLiteral(
"Extent" ) );
613 mapElem.appendChild( extentElem );
617 QDomElement crsElem = doc.createElement( QStringLiteral(
"crs" ) );
619 mapElem.appendChild( crsElem );
623 mapElem.setAttribute( QStringLiteral(
"followPreset" ), mFollowVisibilityPreset ? QStringLiteral(
"true" ) : QStringLiteral(
"false" ) );
624 mapElem.setAttribute( QStringLiteral(
"followPresetName" ), mFollowVisibilityPresetName );
627 mapElem.setAttribute( QStringLiteral(
"mapRotation" ), QString::number( mMapRotation ) );
630 QDomElement layerSetElem = doc.createElement( QStringLiteral(
"LayerSet" ) );
635 QDomElement layerElem = doc.createElement( QStringLiteral(
"Layer" ) );
636 QDomText layerIdText = doc.createTextNode( layerRef.layerId );
637 layerElem.appendChild( layerIdText );
639 layerElem.setAttribute( QStringLiteral(
"name" ), layerRef.name );
640 layerElem.setAttribute( QStringLiteral(
"source" ), layerRef.source );
641 layerElem.setAttribute( QStringLiteral(
"provider" ), layerRef.provider );
643 layerSetElem.appendChild( layerElem );
645 mapElem.appendChild( layerSetElem );
648 if ( mKeepLayerStyles )
650 QDomElement stylesElem = doc.createElement( QStringLiteral(
"LayerStyles" ) );
651 for (
auto styleIt = mLayerStyleOverrides.constBegin(); styleIt != mLayerStyleOverrides.constEnd(); ++styleIt )
653 QDomElement styleElem = doc.createElement( QStringLiteral(
"LayerStyle" ) );
658 styleElem.setAttribute( QStringLiteral(
"layerid" ), ref.
layerId );
659 styleElem.setAttribute( QStringLiteral(
"name" ), ref.
name );
660 styleElem.setAttribute( QStringLiteral(
"source" ), ref.
source );
661 styleElem.setAttribute( QStringLiteral(
"provider" ), ref.
provider );
665 stylesElem.appendChild( styleElem );
667 mapElem.appendChild( stylesElem );
671 mGridStack->writeXml( mapElem, doc, context );
674 mOverviewStack->writeXml( mapElem, doc, context );
677 QDomElement atlasElem = doc.createElement( QStringLiteral(
"AtlasMap" ) );
678 atlasElem.setAttribute( QStringLiteral(
"atlasDriven" ), mAtlasDriven );
679 atlasElem.setAttribute( QStringLiteral(
"scalingMode" ), mAtlasScalingMode );
680 atlasElem.setAttribute( QStringLiteral(
"margin" ),
qgsDoubleToString( mAtlasMargin ) );
681 mapElem.appendChild( atlasElem );
683 mapElem.setAttribute( QStringLiteral(
"labelMargin" ), mLabelMargin.
encodeMeasurement() );
684 mapElem.setAttribute( QStringLiteral(
"mapFlags" ),
static_cast< int>( mMapFlags ) );
686 QDomElement labelBlockingItemsElem = doc.createElement( QStringLiteral(
"labelBlockingItems" ) );
687 for (
const auto &item : std::as_const( mBlockingLabelItems ) )
692 QDomElement blockingItemElem = doc.createElement( QStringLiteral(
"item" ) );
693 blockingItemElem.setAttribute( QStringLiteral(
"uuid" ), item->uuid() );
694 labelBlockingItemsElem.appendChild( blockingItemElem );
696 mapElem.appendChild( labelBlockingItemsElem );
699 mapElem.setAttribute( QStringLiteral(
"isTemporal" ),
isTemporal() ? 1 : 0 );
702 mapElem.setAttribute( QStringLiteral(
"temporalRangeBegin" ),
temporalRange().begin().toString( Qt::ISODate ) );
703 mapElem.setAttribute( QStringLiteral(
"temporalRangeEnd" ),
temporalRange().end().toString( Qt::ISODate ) );
706 mAtlasClippingSettings->
writeXml( mapElem, doc, context );
707 mItemClippingSettings->
writeXml( mapElem, doc, context );
714 mUpdatesEnabled =
false;
717 QDomNodeList extentNodeList = itemElem.elementsByTagName( QStringLiteral(
"Extent" ) );
718 if ( !extentNodeList.isEmpty() )
720 QDomElement extentElem = extentNodeList.at( 0 ).toElement();
721 double xmin, xmax, ymin, ymax;
722 xmin = extentElem.attribute( QStringLiteral(
"xmin" ) ).toDouble();
723 xmax = extentElem.attribute( QStringLiteral(
"xmax" ) ).toDouble();
724 ymin = extentElem.attribute( QStringLiteral(
"ymin" ) ).toDouble();
725 ymax = extentElem.attribute( QStringLiteral(
"ymax" ) ).toDouble();
729 QDomNodeList crsNodeList = itemElem.elementsByTagName( QStringLiteral(
"crs" ) );
731 if ( !crsNodeList.isEmpty() )
733 QDomElement crsElem = crsNodeList.at( 0 ).toElement();
739 mMapRotation = itemElem.attribute( QStringLiteral(
"mapRotation" ), QStringLiteral(
"0" ) ).toDouble();
740 mEvaluatedMapRotation = mMapRotation;
743 mFollowVisibilityPreset = itemElem.attribute( QStringLiteral(
"followPreset" ) ).compare( QLatin1String(
"true" ) ) == 0;
744 mFollowVisibilityPresetName = itemElem.attribute( QStringLiteral(
"followPresetName" ) );
747 QString keepLayerSetFlag = itemElem.attribute( QStringLiteral(
"keepLayerSet" ) );
748 if ( keepLayerSetFlag.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
750 mKeepLayerSet =
true;
754 mKeepLayerSet =
false;
757 QString drawCanvasItemsFlag = itemElem.attribute( QStringLiteral(
"drawCanvasItems" ), QStringLiteral(
"true" ) );
758 if ( drawCanvasItemsFlag.compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0 )
760 mDrawAnnotations =
true;
764 mDrawAnnotations =
false;
767 mLayerStyleOverrides.clear();
771 QDomNodeList layerSetNodeList = itemElem.elementsByTagName( QStringLiteral(
"LayerSet" ) );
772 if ( !layerSetNodeList.isEmpty() )
774 QDomElement layerSetElem = layerSetNodeList.at( 0 ).toElement();
775 QDomNodeList layerIdNodeList = layerSetElem.elementsByTagName( QStringLiteral(
"Layer" ) );
776 mLayers.reserve( layerIdNodeList.size() );
777 for (
int i = 0; i < layerIdNodeList.size(); ++i )
779 QDomElement layerElem = layerIdNodeList.at( i ).toElement();
780 QString layerId = layerElem.text();
781 QString layerName = layerElem.attribute( QStringLiteral(
"name" ) );
782 QString layerSource = layerElem.attribute( QStringLiteral(
"source" ) );
783 QString layerProvider = layerElem.attribute( QStringLiteral(
"provider" ) );
785 QgsMapLayerRef ref( layerId, layerName, layerSource, layerProvider );
792 QDomNodeList layerStylesNodeList = itemElem.elementsByTagName( QStringLiteral(
"LayerStyles" ) );
793 mKeepLayerStyles = !layerStylesNodeList.isEmpty();
794 if ( mKeepLayerStyles )
796 QDomElement layerStylesElem = layerStylesNodeList.at( 0 ).toElement();
797 QDomNodeList layerStyleNodeList = layerStylesElem.elementsByTagName( QStringLiteral(
"LayerStyle" ) );
798 for (
int i = 0; i < layerStyleNodeList.size(); ++i )
800 const QDomElement &layerStyleElement = layerStyleNodeList.at( i ).toElement();
801 QString layerId = layerStyleElement.attribute( QStringLiteral(
"layerid" ) );
802 QString layerName = layerStyleElement.attribute( QStringLiteral(
"name" ) );
803 QString layerSource = layerStyleElement.attribute( QStringLiteral(
"source" ) );
804 QString layerProvider = layerStyleElement.attribute( QStringLiteral(
"provider" ) );
805 QgsMapLayerRef ref( layerId, layerName, layerSource, layerProvider );
809 style.
readXml( layerStyleElement );
815 mNumCachedLayers = 0;
816 mCacheInvalidated =
true;
819 mOverviewStack->readXml( itemElem, doc, context );
822 mGridStack->readXml( itemElem, doc, context );
825 QDomNodeList atlasNodeList = itemElem.elementsByTagName( QStringLiteral(
"AtlasMap" ) );
826 if ( !atlasNodeList.isEmpty() )
828 QDomElement atlasElem = atlasNodeList.at( 0 ).toElement();
829 mAtlasDriven = ( atlasElem.attribute( QStringLiteral(
"atlasDriven" ), QStringLiteral(
"0" ) ) != QLatin1String(
"0" ) );
830 if ( atlasElem.hasAttribute( QStringLiteral(
"fixedScale" ) ) )
832 mAtlasScalingMode = ( atlasElem.attribute( QStringLiteral(
"fixedScale" ), QStringLiteral(
"0" ) ) != QLatin1String(
"0" ) ) ?
Fixed :
Auto;
834 else if ( atlasElem.hasAttribute( QStringLiteral(
"scalingMode" ) ) )
836 mAtlasScalingMode =
static_cast<AtlasScalingMode>( atlasElem.attribute( QStringLiteral(
"scalingMode" ) ).toInt() );
838 mAtlasMargin = atlasElem.attribute( QStringLiteral(
"margin" ), QStringLiteral(
"0.1" ) ).toDouble();
843 mMapFlags =
static_cast< MapItemFlags
>( itemElem.attribute( QStringLiteral(
"mapFlags" ),
nullptr ).toInt() );
846 mBlockingLabelItems.clear();
847 mBlockingLabelItemUuids.clear();
848 QDomNodeList labelBlockingNodeList = itemElem.elementsByTagName( QStringLiteral(
"labelBlockingItems" ) );
849 if ( !labelBlockingNodeList.isEmpty() )
851 QDomElement blockingItems = labelBlockingNodeList.at( 0 ).toElement();
852 QDomNodeList labelBlockingNodeList = blockingItems.childNodes();
853 for (
int i = 0; i < labelBlockingNodeList.size(); ++i )
855 const QDomElement &itemBlockingElement = labelBlockingNodeList.at( i ).toElement();
856 const QString itemUuid = itemBlockingElement.attribute( QStringLiteral(
"uuid" ) );
857 mBlockingLabelItemUuids << itemUuid;
861 mAtlasClippingSettings->
readXml( itemElem, doc, context );
862 mItemClippingSettings->
readXml( itemElem, doc, context );
867 setIsTemporal( itemElem.attribute( QStringLiteral(
"isTemporal" ) ).toInt() );
870 const QDateTime begin = QDateTime::fromString( itemElem.attribute( QStringLiteral(
"temporalRangeBegin" ) ), Qt::ISODate );
871 const QDateTime end = QDateTime::fromString( itemElem.attribute( QStringLiteral(
"temporalRangeEnd" ) ), Qt::ISODate );
875 mUpdatesEnabled =
true;
881 if ( mItemClippingSettings->
isActive() )
892 if ( !
mLayout || !painter || !painter->device() || !mUpdatesEnabled )
901 QRectF thisPaintRect = rect();
907 if (
mLayout->renderContext().isPreviewRender() )
910 painter->setClipRect( thisPaintRect );
911 if ( !mCacheFinalImage || mCacheFinalImage->isNull() )
914 painter->setBrush( QBrush( QColor( 125, 125, 125, 125 ) ) );
915 painter->drawRect( thisPaintRect );
916 painter->setBrush( Qt::NoBrush );
918 messageFont.setPointSize( 12 );
919 painter->setFont( messageFont );
920 painter->setPen( QColor( 255, 255, 255, 255 ) );
921 painter->drawText( thisPaintRect, Qt::AlignCenter | Qt::AlignHCenter, tr(
"Rendering map" ) );
922 if ( mPainterJob && mCacheInvalidated && !mDrawingPreview )
926 mBackgroundUpdateTimer->start( 1 );
928 else if ( !mPainterJob && !mDrawingPreview )
932 mBackgroundUpdateTimer->start( 1 );
937 if ( mCacheInvalidated && !mDrawingPreview )
941 mBackgroundUpdateTimer->start( 1 );
946 double imagePixelWidth = mCacheFinalImage->width();
947 double scale = rect().width() / imagePixelWidth;
951 painter->translate( mLastRenderedImageOffsetX + mXOffset, mLastRenderedImageOffsetY + mYOffset );
953 painter->drawImage( 0, 0, *mCacheFinalImage );
958 painter->setClipRect( thisPaintRect, Qt::NoClip );
960 mOverviewStack->drawItems( painter,
false );
961 mGridStack->drawItems( painter );
963 drawMapFrame( painter );
971 QPaintDevice *paintDevice = painter->device();
978 #if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)
980 painter->setRenderHint( QPainter::LosslessImageRendering,
true );
988 int widthInPixels =
static_cast< int >( std::round(
boundingRect().width() * layoutUnitsInInches * destinationDpi ) );
989 int heightInPixels =
static_cast< int >( std::round(
boundingRect().height() * layoutUnitsInInches * destinationDpi ) );
990 QImage image = QImage( widthInPixels, heightInPixels, QImage::Format_ARGB32 );
992 image.fill( Qt::transparent );
993 image.setDotsPerMeterX(
static_cast< int >( std::round( 1000 * destinationDpi / 25.4 ) ) );
994 image.setDotsPerMeterY(
static_cast< int >( std::round( 1000 * destinationDpi / 25.4 ) ) );
995 double dotsPerMM = destinationDpi / 25.4;
996 QPainter p( &image );
999 QRect imagePaintRect(
static_cast< int >( std::round( tl.x() * dotsPerMM ) ),
1000 static_cast< int >( std::round( tl.y() * dotsPerMM ) ),
1001 static_cast< int >( std::round( thisPaintRect.width() * dotsPerMM ) ),
1002 static_cast< int >( std::round( thisPaintRect.height() * dotsPerMM ) ) );
1003 p.setClipRect( imagePaintRect );
1005 p.translate( imagePaintRect.topLeft() );
1009 if ( shouldDrawPart( Background ) )
1011 p.scale( dotsPerMM, dotsPerMM );
1012 drawMapBackground( &p );
1013 p.scale( 1.0 / dotsPerMM, 1.0 / dotsPerMM );
1016 drawMap( &p, cExtent, imagePaintRect.size(), image.logicalDpiX() );
1021 p.scale( dotsPerMM, dotsPerMM );
1023 if ( shouldDrawPart( OverviewMapExtent ) )
1025 mOverviewStack->drawItems( &p,
false );
1027 if ( shouldDrawPart( Grid ) )
1029 mGridStack->drawItems( &p );
1034 painter->scale( 1 / dotsPerMM, 1 / dotsPerMM );
1035 painter->drawImage( QPointF( -tl.x()* dotsPerMM, -tl.y() * dotsPerMM ), image );
1036 painter->scale( dotsPerMM, dotsPerMM );
1041 if ( shouldDrawPart( Background ) )
1043 drawMapBackground( painter );
1047 painter->setClipRect( thisPaintRect );
1052 painter->translate( mXOffset, mYOffset );
1054 double dotsPerMM = paintDevice->logicalDpiX() / 25.4;
1056 painter->scale( 1 / dotsPerMM, 1 / dotsPerMM );
1058 if ( mCurrentExportPart != NotLayered )
1060 if ( !mStagedRendererJob )
1062 createStagedRenderJob( cExtent, size, paintDevice->logicalDpiX() );
1065 mStagedRendererJob->renderCurrentPart( painter );
1069 drawMap( painter, cExtent, size, paintDevice->logicalDpiX() );
1073 painter->setClipRect( thisPaintRect, Qt::NoClip );
1075 if ( shouldDrawPart( OverviewMapExtent ) )
1077 mOverviewStack->drawItems( painter,
false );
1079 if ( shouldDrawPart( Grid ) )
1081 mGridStack->drawItems( painter );
1086 if ( shouldDrawPart( Frame ) )
1088 drawMapFrame( painter );
1099 + ( layerCount + ( layerCount ? 1 : 0 ) )
1100 + ( mGridStack->hasEnabledItems() ? 1 : 0 )
1101 + ( mOverviewStack->hasEnabledItems() ? 1 : 0 )
1107 mCurrentExportPart = Start;
1109 mExportThemes = !mFollowVisibilityPreset ?
mLayout->renderContext().exportThemes() : QStringList();
1110 mExportThemeIt = mExportThemes.begin();
1115 mCurrentExportPart = NotLayered;
1116 mExportThemes.clear();
1117 mExportThemeIt = mExportThemes.begin();
1122 switch ( mCurrentExportPart )
1127 mCurrentExportPart = Background;
1133 mCurrentExportPart = Layer;
1137 if ( mStagedRendererJob )
1139 if ( mStagedRendererJob->nextPart() )
1143 mExportLabelingResults.reset( mStagedRendererJob->takeLabelingResults() );
1144 mStagedRendererJob.reset();
1148 if ( mExportThemeIt != mExportThemes.end() && ++mExportThemeIt != mExportThemes.end() )
1154 if ( mGridStack->hasEnabledItems() )
1156 mCurrentExportPart = Grid;
1162 for (
int i = 0; i < mOverviewStack->size(); ++i )
1167 mCurrentExportPart = OverviewMapExtent;
1173 case OverviewMapExtent:
1176 mCurrentExportPart = Frame;
1183 if ( isSelected() && !
mLayout->renderContext().isPreviewRender() )
1185 mCurrentExportPart = SelectionBoxes;
1190 case SelectionBoxes:
1191 mCurrentExportPart = End;
1212 switch ( mCurrentExportPart )
1222 if ( !mExportThemes.empty() && mExportThemeIt != mExportThemes.end() )
1225 if ( mStagedRendererJob )
1227 switch ( mStagedRendererJob->currentStage() )
1231 detail.
mapLayerId = mStagedRendererJob->currentLayerId();
1232 detail.
compositionMode = mStagedRendererJob->currentLayerCompositionMode();
1233 detail.
opacity = mStagedRendererJob->currentLayerOpacity();
1239 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), layer->name() );
1241 else if (
mLayout->project()->mainAnnotationLayer()->id() == detail.
mapLayerId )
1247 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), tr(
"Annotations" ) );
1252 const QList<QgsLayoutItemMapOverview *> res = mOverviewStack->asList();
1258 if ( item->mapLayer() && detail.
mapLayerId == item->mapLayer()->id() )
1261 detail.
name = QStringLiteral(
"%1 (%2): %3" ).arg(
displayName(), detail.
mapTheme, item->mapLayer()->name() );
1263 detail.
name = QStringLiteral(
"%1: %2" ).arg(
displayName(), item->mapLayer()->name() );
1272 detail.
mapLayerId = mStagedRendererJob->currentLayerId();
1278 detail.
name = tr(
"%1: %2 (Labels)" ).arg(
displayName(), layer->name() );
1313 case OverviewMapExtent:
1321 case SelectionBoxes:
1336 void QgsLayoutItemMap::drawMap( QPainter *painter,
const QgsRectangle &extent, QSizeF size,
double dpi )
1350 if ( shouldDrawPart( OverviewMapExtent ) )
1352 ms.setLayers( mOverviewStack->modifyMapLayerList( ms.layers() ) );
1356 #ifdef HAVE_SERVER_PYTHON_PLUGINS
1357 job.setFeatureFilterProvider(
mLayout->renderContext().featureFilterProvider() );
1363 job.renderSynchronously();
1365 mExportLabelingResults.reset( job.takeLabelingResults() );
1367 mRenderingErrors = job.errors();
1370 void QgsLayoutItemMap::recreateCachedImageInBackground()
1376 QPainter *oldPainter = mPainter.release();
1377 QImage *oldImage = mCacheRenderingImage.release();
1380 oldJob->deleteLater();
1388 mCacheRenderingImage.reset(
nullptr );
1392 Q_ASSERT( !mPainterJob );
1393 Q_ASSERT( !mPainter );
1394 Q_ASSERT( !mCacheRenderingImage );
1400 int w =
static_cast< int >( std::round( widthLayoutUnits * mPreviewScaleFactor ) );
1401 int h =
static_cast< int >( std::round( heightLayoutUnits * mPreviewScaleFactor ) );
1404 if ( w > 5000 || h > 5000 )
1409 h =
static_cast< int>( std::round( w * heightLayoutUnits / widthLayoutUnits ) );
1414 w =
static_cast< int >( std::round( h * widthLayoutUnits / heightLayoutUnits ) );
1418 if ( w <= 0 || h <= 0 )
1421 mCacheRenderingImage.reset(
new QImage( w, h, QImage::Format_ARGB32 ) );
1424 mCacheRenderingImage->setDotsPerMeterX(
static_cast< int >( std::round( 1000 * w / widthLayoutUnits ) ) );
1425 mCacheRenderingImage->setDotsPerMeterY(
static_cast< int >( std::round( 1000 * h / heightLayoutUnits ) ) );
1428 mCacheRenderingImage->fill( QColor( 255, 255, 255, 0 ).rgba() );
1433 if ( mItemClippingSettings->
isActive() )
1435 QPainter p( mCacheRenderingImage.get() );
1437 p.setPen( Qt::NoPen );
1439 p.scale( mCacheRenderingImage->width() / widthLayoutUnits, mCacheRenderingImage->height() / heightLayoutUnits );
1449 mCacheInvalidated =
false;
1450 mPainter.reset(
new QPainter( mCacheRenderingImage.get() ) );
1453 if ( shouldDrawPart( OverviewMapExtent ) )
1455 settings.setLayers( mOverviewStack->modifyMapLayerList( settings.layers() ) );
1460 mPainterJob->start();
1472 mDrawingPreview =
false;
1495 if (
layout()->renderContext().isPreviewRender() )
1498 jobMapSettings.
setRotation( mEvaluatedMapRotation );
1502 if ( includeLayerSettings )
1507 if ( !
mLayout->project()->mainAnnotationLayer()->isEmpty() )
1510 layers.insert( 0,
mLayout->project()->mainAnnotationLayer() );
1517 if ( !
mLayout->renderContext().isPreviewRender() )
1555 if ( mEvaluatedLabelMargin.
length() > 0 )
1558 visiblePoly.append( visiblePoly.at( 0 ) );
1559 const double layoutLabelMargin =
mLayout->convertToLayoutUnits( mEvaluatedLabelMargin );
1560 const double layoutLabelMarginInMapUnits = layoutLabelMargin / rect().width() * jobMapSettings.
extent().
width();
1562 mapBoundaryGeom = mapBoundaryGeom.
buffer( -layoutLabelMarginInMapUnits, 0 );
1563 labelBoundary = mapBoundaryGeom;
1566 if ( !mBlockingLabelItems.isEmpty() )
1579 if ( mAtlasClippingSettings->
enabled() &&
mLayout->reportContext().feature().isValid() )
1590 if ( !labelBoundary.
isEmpty() )
1592 labelBoundary = clipGeom.
intersection( labelBoundary );
1596 labelBoundary = clipGeom;
1601 if ( mItemClippingSettings->
isActive() )
1610 const double layoutLabelMargin =
mLayout->convertToLayoutUnits( mEvaluatedLabelMargin );
1611 const double layoutLabelMarginInMapUnits = layoutLabelMargin / rect().width() * jobMapSettings.
extent().
width();
1613 mapBoundaryGeom = mapBoundaryGeom.
buffer( -layoutLabelMarginInMapUnits, 0 );
1614 if ( !labelBoundary.
isEmpty() )
1616 labelBoundary = mapBoundaryGeom.
intersection( labelBoundary );
1620 labelBoundary = mapBoundaryGeom;
1626 if ( !labelBoundary.
isNull() )
1629 return jobMapSettings;
1636 mBlockingLabelItems.clear();
1637 for (
const QString &
uuid : std::as_const( mBlockingLabelItemUuids ) )
1646 mOverviewStack->finalizeRestoreFromXml();
1647 mGridStack->finalizeRestoreFromXml();
1659 return mCurrentRectangle;
1693 QVariantList layersIds;
1703 const QList<QgsMapLayer *> layersInMap =
layersToRender( &context );
1705 layersIds.reserve( layersInMap.count() );
1706 layers.reserve( layersInMap.count() );
1709 layersIds << layer->id();
1715 scope->
addFunction( QStringLiteral(
"is_layer_visible" ),
new QgsExpressionContextUtils::GetLayerVisibility( layersInMap,
scale() ) );
1727 if ( extentWidth <= 0 )
1731 return rect().width() / extentWidth;
1736 double dx = mXOffset;
1737 double dy = mYOffset;
1738 transformShift( dx, dy );
1739 QPolygonF poly = calculateVisibleExtentPolygon(
false );
1740 poly.translate( -dx, -dy );
1746 if ( !mBlockingLabelItems.contains( item ) )
1747 mBlockingLabelItems.append( item );
1754 mBlockingLabelItems.removeAll( item );
1761 return mBlockingLabelItems.contains( item );
1766 return mPreviewLabelingResults.get();
1775 if ( mOverviewStack )
1777 for (
int i = 0; i < mOverviewStack->size(); ++i )
1779 if ( mOverviewStack->item( i )->accept( visitor ) )
1786 for (
int i = 0; i < mGridStack->size(); ++i )
1788 if ( mGridStack->item( i )->accept( visitor ) )
1801 mRenderedFeatureHandlers.append( handler );
1806 mRenderedFeatureHandlers.removeAll( handler );
1812 if ( mapPoly.empty() )
1814 return QPointF( 0, 0 );
1819 double dx = mapCoords.x() - rotationPoint.
x();
1820 double dy = mapCoords.y() - rotationPoint.
y();
1822 QgsPointXY backRotatedCoords( rotationPoint.
x() + dx, rotationPoint.
y() + dy );
1825 double xItem = rect().width() * ( backRotatedCoords.
x() - unrotatedExtent.
xMinimum() ) / unrotatedExtent.
width();
1826 double yItem = rect().height() * ( 1 - ( backRotatedCoords.
y() - unrotatedExtent.
yMinimum() ) / unrotatedExtent.
height() );
1827 return QPointF( xItem, yItem );
1841 mapPolygon( newExtent, poly );
1842 QRectF bRect = poly.boundingRect();
1856 mCacheInvalidated =
true;
1862 QRectF rectangle = rect();
1863 double frameExtension =
frameEnabled() ? pen().widthF() / 2.0 : 0.0;
1865 double topExtension = 0.0;
1866 double rightExtension = 0.0;
1867 double bottomExtension = 0.0;
1868 double leftExtension = 0.0;
1871 mGridStack->calculateMaxGridExtension( topExtension, rightExtension, bottomExtension, leftExtension );
1873 topExtension = std::max( topExtension, frameExtension );
1874 rightExtension = std::max( rightExtension, frameExtension );
1875 bottomExtension = std::max( bottomExtension, frameExtension );
1876 leftExtension = std::max( leftExtension, frameExtension );
1878 rectangle.setLeft( rectangle.left() - leftExtension );
1879 rectangle.setRight( rectangle.right() + rightExtension );
1880 rectangle.setTop( rectangle.top() - topExtension );
1881 rectangle.setBottom( rectangle.bottom() + bottomExtension );
1882 if ( rectangle != mCurrentRectangle )
1884 prepareGeometryChange();
1885 mCurrentRectangle = rectangle;
1913 refreshMapExtents( &context );
1915 if ( mExtent != beforeExtent )
1922 refreshLabelMargin(
false );
1926 const QString previousTheme = mLastEvaluatedThemeName.isEmpty() ? mFollowVisibilityPresetName : mLastEvaluatedThemeName;
1928 if ( mLastEvaluatedThemeName != previousTheme )
1946 mCacheInvalidated =
true;
1951 void QgsLayoutItemMap::layersAboutToBeRemoved(
const QList<QgsMapLayer *> &layers )
1953 if ( !mLayers.isEmpty() || mLayerStyleOverrides.isEmpty() )
1957 mLayerStyleOverrides.remove( layer->id() );
1959 _qgis_removeLayers( mLayers,
layers );
1963 void QgsLayoutItemMap::painterJobFinished()
1966 mPreviewLabelingResults.reset( mPainterJob->takeLabelingResults() );
1967 mPainterJob.reset(
nullptr );
1968 mPainter.reset(
nullptr );
1969 mCacheFinalImage = std::move( mCacheRenderingImage );
1970 mLastRenderedImageOffsetX = 0;
1971 mLastRenderedImageOffsetY = 0;
1977 void QgsLayoutItemMap::shapeChanged()
1982 double w = rect().width();
1983 double h = rect().height();
1986 double newWidth = mExtent.
width();
1988 double newHeight = newWidth * h / w;
1993 refreshMapExtents();
2000 void QgsLayoutItemMap::mapThemeChanged(
const QString &theme )
2002 if ( theme == mCachedLayerStyleOverridesPresetName )
2003 mCachedLayerStyleOverridesPresetName.clear();
2006 void QgsLayoutItemMap::currentMapThemeRenamed(
const QString &theme,
const QString &newTheme )
2008 if ( theme == mFollowVisibilityPresetName )
2010 mFollowVisibilityPresetName = newTheme;
2014 void QgsLayoutItemMap::connectUpdateSlot()
2022 this, &QgsLayoutItemMap::layersAboutToBeRemoved );
2026 if ( layers().isEmpty() )
2055 if ( mAtlasScalingMode == Predefined )
2056 updateAtlasFeature();
2062 QPolygonF thisExtent = calculateVisibleExtentPolygon(
false );
2063 QTransform mapTransform;
2064 QPolygonF thisRectPoly = QPolygonF( QRectF( 0, 0, rect().width(), rect().height() ) );
2066 thisRectPoly.pop_back();
2067 thisExtent.pop_back();
2069 QPolygonF thisItemPolyInLayout = mapToScene( thisRectPoly );
2072 QTransform::quadToQuad( thisItemPolyInLayout, thisExtent, mapTransform );
2073 return mapTransform;
2076 QList<QgsLabelBlockingRegion> QgsLayoutItemMap::createLabelBlockingRegions(
const QgsMapSettings & )
const
2079 QList< QgsLabelBlockingRegion > blockers;
2080 blockers.reserve( mBlockingLabelItems.count() );
2081 for (
const auto &item : std::as_const( mBlockingLabelItems ) )
2088 if ( item->property(
"wasVisible" ).isValid() )
2090 if ( !item->property(
"wasVisible" ).toBool() )
2093 else if ( !item->isVisible() )
2096 QPolygonF itemRectInMapCoordinates = mapTransform.map( item->mapToScene( item->rect() ) );
2097 itemRectInMapCoordinates.append( itemRectInMapCoordinates.at( 0 ) );
2106 return mLabelMargin;
2111 mLabelMargin = margin;
2112 refreshLabelMargin(
false );
2115 void QgsLayoutItemMap::updateToolTip()
2124 if ( mFollowVisibilityPreset )
2126 presetName = mFollowVisibilityPresetName;
2130 else if ( !mExportThemes.empty() && mExportThemeIt != mExportThemes.end() )
2131 presetName = *mExportThemeIt;
2142 QList<QgsMapLayer *> renderLayers;
2144 QString presetName = themeToRender( *evalContext );
2145 if ( !presetName.isEmpty() )
2147 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
2148 renderLayers =
mLayout->project()->mapThemeCollection()->mapThemeVisibleLayers( presetName );
2150 renderLayers =
mLayout->project()->mapThemeCollection()->masterVisibleLayers();
2152 else if ( !
layers().isEmpty() )
2158 renderLayers =
mLayout->project()->mapThemeCollection()->masterVisibleLayers();
2165 renderLayers.clear();
2167 const QStringList layerNames = ddLayers.split(
'|' );
2169 for (
const QString &name : layerNames )
2171 const QList< QgsMapLayer * > matchingLayers =
mLayout->project()->mapLayersByName( name );
2174 renderLayers << layer;
2183 int removeAt = renderLayers.indexOf(
mLayout->reportContext().layer() );
2184 if ( removeAt != -1 )
2186 renderLayers.removeAt( removeAt );
2191 renderLayers.erase( std::remove_if( renderLayers.begin(), renderLayers.end(), [](
QgsMapLayer * layer )
2193 return !layer || !layer->isValid();
2194 } ), renderLayers.end() );
2196 return renderLayers;
2199 QMap<QString, QString> QgsLayoutItemMap::layerStyleOverridesToRender(
const QgsExpressionContext &context )
const
2201 QString presetName = themeToRender( context );
2202 if ( !presetName.isEmpty() )
2204 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
2206 if ( presetName != mCachedLayerStyleOverridesPresetName )
2209 mCachedPresetLayerStyleOverrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( presetName );
2210 mCachedLayerStyleOverridesPresetName = presetName;
2213 return mCachedPresetLayerStyleOverrides;
2216 return QMap<QString, QString>();
2218 else if ( mFollowVisibilityPreset )
2220 QString presetName = mFollowVisibilityPresetName;
2223 if (
mLayout->project()->mapThemeCollection()->hasMapTheme( presetName ) )
2225 if ( presetName.isEmpty() || presetName != mCachedLayerStyleOverridesPresetName )
2228 mCachedPresetLayerStyleOverrides =
mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( presetName );
2229 mCachedLayerStyleOverridesPresetName = presetName;
2232 return mCachedPresetLayerStyleOverrides;
2235 return QMap<QString, QString>();
2237 else if ( mKeepLayerStyles )
2239 return mLayerStyleOverrides;
2243 return QMap<QString, QString>();
2247 QgsRectangle QgsLayoutItemMap::transformedExtent()
const
2249 double dx = mXOffset;
2250 double dy = mYOffset;
2251 transformShift( dx, dy );
2255 void QgsLayoutItemMap::mapPolygon(
const QgsRectangle &extent, QPolygonF &poly )
const
2265 poly << QPointF( poly.at( 0 ) );
2277 poly << QPointF( rotationPoint.x() - dx, rotationPoint.y() - dy );
2283 poly << QPointF( rotationPoint.x() - dx, rotationPoint.y() - dy );
2289 poly << QPointF( rotationPoint.x() - dx, rotationPoint.y() - dy );
2295 poly << QPointF( rotationPoint.x() - dx, rotationPoint.y() - dy );
2298 poly << QPointF( poly.at( 0 ) );
2301 void QgsLayoutItemMap::transformShift(
double &xShift,
double &yShift )
const
2304 double dxScaled = xShift * mmToMapUnits;
2305 double dyScaled = - yShift * mmToMapUnits;
2320 const QList< QgsAnnotation * > annotations =
mLayout->project()->annotationManager()->annotations();
2321 if ( annotations.isEmpty() )
2331 if ( !annotation || !annotation->isVisible() )
2335 if ( annotation->mapLayer() && !
layers.contains( annotation->mapLayer() ) )
2338 drawAnnotation( annotation, rc );
2352 double itemX, itemY;
2355 QPointF mapPos = layoutMapPosForItem( annotation );
2364 context.
painter()->translate( itemX, itemY );
2367 double dotsPerMM = context.
painter()->device()->logicalDpiX() / 25.4;
2368 context.
painter()->scale( 1 / dotsPerMM, 1 / dotsPerMM );
2370 annotation->
render( context );
2373 QPointF QgsLayoutItemMap::layoutMapPosForItem(
const QgsAnnotation *annotation )
const
2376 return QPointF( 0, 0 );
2385 if ( annotationCrs !=
crs() )
2392 t.transformInPlace( mapX, mapY, z );
2402 void QgsLayoutItemMap::drawMapFrame( QPainter *p )
2413 void QgsLayoutItemMap::drawMapBackground( QPainter *p )
2424 bool QgsLayoutItemMap::shouldDrawPart( QgsLayoutItemMap::PartType part )
const
2426 if ( mCurrentExportPart == NotLayered )
2444 return mCurrentExportPart == Layer;
2447 return mCurrentExportPart == Grid && mGridStack->hasEnabledItems();
2449 case OverviewMapExtent:
2450 return mCurrentExportPart == OverviewMapExtent && mOverviewStack->hasEnabledItems();
2455 case SelectionBoxes:
2456 return mCurrentExportPart == SelectionBoxes && isSelected();
2477 bool useDdXMin =
false;
2478 bool useDdXMax =
false;
2479 bool useDdYMin =
false;
2480 bool useDdYMax =
false;
2511 if ( newExtent != mExtent )
2517 double currentWidthHeightRatio = mExtent.
width() / mExtent.
height();
2518 double newWidthHeightRatio = newExtent.
width() / newExtent.
height();
2520 if ( currentWidthHeightRatio < newWidthHeightRatio )
2523 double newHeight = newExtent.
width() / currentWidthHeightRatio;
2524 double deltaHeight = newHeight - newExtent.
height();
2531 double newWidth = currentWidthHeightRatio * newExtent.
height();
2532 double deltaWidth = newWidth - newExtent.
width();
2537 mExtent = newExtent;
2547 newExtent = mExtent;
2550 if ( useDdXMax || useDdXMin || useDdYMax || useDdYMin )
2554 if ( useDdXMin && !useDdXMax )
2560 else if ( !useDdXMin && useDdXMax )
2566 if ( useDdYMin && !useDdYMax )
2572 else if ( !useDdYMin && useDdYMax )
2579 if ( newExtent != mExtent )
2581 mExtent = newExtent;
2598 void QgsLayoutItemMap::refreshLabelMargin(
bool updateItem )
2611 void QgsLayoutItemMap::updateAtlasFeature()
2630 if ( mAtlasScalingMode ==
Fixed || mAtlasScalingMode ==
Predefined || isPointLayer )
2635 double originalScale = calc.
calculate( originalExtent, rect().width() );
2636 double geomCenterX = ( xa1 + xa2 ) / 2.0;
2637 double geomCenterY = ( ya1 + ya2 ) / 2.0;
2638 QVector<qreal> scales;
2640 if ( !
mLayout->reportContext().predefinedScales().empty() )
2641 scales =
mLayout->reportContext().predefinedScales();
2643 scales =
mLayout->renderContext().predefinedScales();
2645 if ( mAtlasScalingMode ==
Fixed || isPointLayer || scales.isEmpty() )
2648 double xMin = geomCenterX - originalExtent.
width() / 2.0;
2649 double yMin = geomCenterY - originalExtent.
height() / 2.0;
2652 xMin + originalExtent.
width(),
2653 yMin + originalExtent.
height() );
2657 double newScale = calc.
calculate( newExtent, rect().width() );
2658 newExtent.
scale( originalScale / newScale );
2663 double newWidth = originalExtent.
width();
2664 double newHeight = originalExtent.
height();
2665 for (
int i = 0; i < scales.size(); i++ )
2667 double ratio = scales[i] / originalScale;
2668 newWidth = originalExtent.
width() * ratio;
2669 newHeight = originalExtent.
height() * ratio;
2672 double xMin = geomCenterX - newWidth / 2.0;
2673 double yMin = geomCenterY - newHeight / 2.0;
2681 double newScale = calc.
calculate( newExtent, rect().width() );
2682 newExtent.
scale( scales[i] / newScale );
2692 else if ( mAtlasScalingMode ==
Auto )
2696 double geomRatio = bounds.
width() / bounds.
height();
2697 double mapRatio = originalExtent.
width() / originalExtent.
height();
2700 if ( geomRatio < mapRatio )
2703 double adjWidth = ( mapRatio * bounds.
height() - bounds.
width() ) / 2.0;
2708 else if ( geomRatio > mapRatio )
2711 double adjHeight = ( bounds.
width() / mapRatio - bounds.
height() ) / 2.0;
2717 const double evaluatedAtlasMargin =
atlasMargin();
2718 if ( evaluatedAtlasMargin > 0.0 )
2720 newExtent.
scale( 1 + evaluatedAtlasMargin );
2736 if ( mEvaluatedMapRotation != 0.0 )
2746 double dx = std::max( std::abs( prevCenter.
x() - bounds.
xMinimum() ),
2747 std::abs( prevCenter.
x() - bounds.
xMaximum() ) );
2748 double dy = std::max( std::abs( prevCenter.
y() - bounds.
yMinimum() ),
2749 std::abs( prevCenter.
y() - bounds.
yMaximum() ) );
2752 center.
x() + dx, center.
y() + dy );
2760 void QgsLayoutItemMap::createStagedRenderJob(
const QgsRectangle &extent,
const QSizeF size,
double dpi )
2763 settings.
setLayers( mOverviewStack->modifyMapLayerList( settings.
layers() ) );
2765 mStagedRendererJob = std::make_unique< QgsMapRendererStagedRenderJob >( settings,
2768 : QgsMapRendererStagedRenderJob::Flags() );
2769 mStagedRendererJob->start();
2785 this, &QgsLayoutItemMapAtlasClippingSettings::layersAboutToBeRemoved );
2791 return mClipToAtlasFeature;
2796 if (
enabled == mClipToAtlasFeature )
2799 mClipToAtlasFeature =
enabled;
2805 return mFeatureClippingType;
2810 if ( mFeatureClippingType == type )
2813 mFeatureClippingType = type;
2819 return mForceLabelsInsideFeature;
2824 if ( forceInside == mForceLabelsInsideFeature )
2827 mForceLabelsInsideFeature = forceInside;
2833 return mRestrictToLayers;
2838 if ( mRestrictToLayers ==
enabled )
2847 return _qgis_listRefToRaw( mLayersToClip );
2858 QDomElement settingsElem = document.createElement( QStringLiteral(
"atlasClippingSettings" ) );
2859 settingsElem.setAttribute( QStringLiteral(
"enabled" ), mClipToAtlasFeature ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
2860 settingsElem.setAttribute( QStringLiteral(
"forceLabelsInside" ), mForceLabelsInsideFeature ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
2861 settingsElem.setAttribute( QStringLiteral(
"clippingType" ), QString::number(
static_cast<int>( mFeatureClippingType ) ) );
2862 settingsElem.setAttribute( QStringLiteral(
"restrictLayers" ), mRestrictToLayers ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
2865 QDomElement layerSetElem = document.createElement( QStringLiteral(
"layersToClip" ) );
2870 QDomElement layerElem = document.createElement( QStringLiteral(
"Layer" ) );
2871 QDomText layerIdText = document.createTextNode( layerRef.layerId );
2872 layerElem.appendChild( layerIdText );
2874 layerElem.setAttribute( QStringLiteral(
"name" ), layerRef.name );
2875 layerElem.setAttribute( QStringLiteral(
"source" ), layerRef.source );
2876 layerElem.setAttribute( QStringLiteral(
"provider" ), layerRef.provider );
2878 layerSetElem.appendChild( layerElem );
2880 settingsElem.appendChild( layerSetElem );
2882 element.appendChild( settingsElem );
2888 const QDomElement settingsElem = element.firstChildElement( QStringLiteral(
"atlasClippingSettings" ) );
2890 mClipToAtlasFeature = settingsElem.attribute( QStringLiteral(
"enabled" ), QStringLiteral(
"0" ) ).toInt();
2891 mForceLabelsInsideFeature = settingsElem.attribute( QStringLiteral(
"forceLabelsInside" ), QStringLiteral(
"0" ) ).toInt();
2893 mRestrictToLayers = settingsElem.attribute( QStringLiteral(
"restrictLayers" ), QStringLiteral(
"0" ) ).toInt();
2895 mLayersToClip.clear();
2896 QDomNodeList layerSetNodeList = settingsElem.elementsByTagName( QStringLiteral(
"layersToClip" ) );
2897 if ( !layerSetNodeList.isEmpty() )
2899 QDomElement layerSetElem = layerSetNodeList.at( 0 ).toElement();
2900 QDomNodeList layerIdNodeList = layerSetElem.elementsByTagName( QStringLiteral(
"Layer" ) );
2901 mLayersToClip.reserve( layerIdNodeList.size() );
2902 for (
int i = 0; i < layerIdNodeList.size(); ++i )
2904 QDomElement layerElem = layerIdNodeList.at( i ).toElement();
2905 QString layerId = layerElem.text();
2906 QString layerName = layerElem.attribute( QStringLiteral(
"name" ) );
2907 QString layerSource = layerElem.attribute( QStringLiteral(
"source" ) );
2908 QString layerProvider = layerElem.attribute( QStringLiteral(
"provider" ) );
2910 QgsMapLayerRef ref( layerId, layerName, layerSource, layerProvider );
2913 mLayersToClip << ref;
2920 void QgsLayoutItemMapAtlasClippingSettings::layersAboutToBeRemoved(
const QList<QgsMapLayer *> &layers )
2922 if ( !mLayersToClip.isEmpty() )
2924 _qgis_removeLayers( mLayersToClip, layers );
2939 return mEnabled && mClipPathSource;
2954 if ( mClipPathSource )
2957 mClipPathSource->refresh();
2966 QgsGeometry clipGeom( mClipPathSource->clipPath() );
2977 QgsGeometry clipGeom( mClipPathSource->clipPath() );
2978 clipGeom.
transform( mMap->sceneTransform().inverted() );
2993 if ( mClipPathSource == item )
2996 if ( mClipPathSource )
3005 mClipPathSource = item;
3007 if ( mClipPathSource )
3016 mClipPathSource->refresh();
3030 return mClipPathSource;
3035 return mFeatureClippingType;
3040 if ( mFeatureClippingType == type )
3043 mFeatureClippingType = type;
3049 return mForceLabelsInsideClipPath;
3054 if ( forceInside == mForceLabelsInsideClipPath )
3057 mForceLabelsInsideClipPath = forceInside;
3063 QDomElement settingsElem = document.createElement( QStringLiteral(
"itemClippingSettings" ) );
3064 settingsElem.setAttribute( QStringLiteral(
"enabled" ), mEnabled ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
3065 settingsElem.setAttribute( QStringLiteral(
"forceLabelsInside" ), mForceLabelsInsideClipPath ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
3066 settingsElem.setAttribute( QStringLiteral(
"clippingType" ), QString::number(
static_cast<int>( mFeatureClippingType ) ) );
3067 if ( mClipPathSource )
3068 settingsElem.setAttribute( QStringLiteral(
"clipSource" ), mClipPathSource->uuid() );
3070 settingsElem.setAttribute( QStringLiteral(
"clipSource" ), QString() );
3072 element.appendChild( settingsElem );
3078 const QDomElement settingsElem = element.firstChildElement( QStringLiteral(
"itemClippingSettings" ) );
3080 mEnabled = settingsElem.attribute( QStringLiteral(
"enabled" ), QStringLiteral(
"0" ) ).toInt();
3081 mForceLabelsInsideClipPath = settingsElem.attribute( QStringLiteral(
"forceLabelsInside" ), QStringLiteral(
"0" ) ).toInt();
3083 mClipPathUuid = settingsElem.attribute( QStringLiteral(
"clipSource" ) );
3090 if ( !mClipPathUuid.isEmpty() )
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 description() const
Returns the descriptive name of the CRS, e.g., "WGS 84" or "GDA 94 / Vicgrid94".
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.
QString authid() const
Returns the authority identifier for the CRS.
@ 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.
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.
OperationResult rotate(double rotation, const QgsPointXY ¢er)
Rotate this geometry around the Z axis.
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.
QgsGeometry intersection(const QgsGeometry &geometry) const
Returns a geometry representing the points shared by this geometry and other.
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 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...
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
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...
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.
void setTextRenderFormat(QgsRenderContext::TextRenderFormat format)
Sets the text render format, which dictates how text is rendered (e.g.
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 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.
@ RenderPartialOutput
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
@ UseRenderingOptimization
Enable vector simplification and other rendering optimizations.
@ LosslessImageRendering
Render images losslessly whenever possible, instead of the default lossy jpeg rendering used for some...
@ Antialiasing
Enable anti-aliasing for map rendering.
@ UseAdvancedEffects
Enable layer opacity and blending effects.
@ DrawSelection
Whether vector selections should be shown in the rendered map.
@ DrawEditingInfo
Enable drawing of vertex markers for layers in editing mode.
@ ForceVectorOutput
Vector graphics should not be cached and drawn as raster images.
void setOutputDpi(double dpi)
Sets the dpi (dots per inch) used for conversion between real world units (e.g.
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.
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.
QList< QgsMapLayer * > layers() const
Returns the list of layers which will be rendered in the map.
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 setFlag(Flag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected)
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 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(QgsPointXY center, 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.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
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 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.
QString source
Weak reference to layer public source.
QString name
Weak reference to layer name.
TYPE * resolve(const QgsProject *project)
Resolves the map layer by attempting to find a layer with matching ID within a project.
QString provider
Weak reference to layer provider.
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 layerId
Original layer ID.