QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgsgrouplayer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsgrouplayer.cpp
3 ----------------
4 Date : September 2021
5 Copyright : (C) 2021 by Nyall Dawson
6 Email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
18#include "qgsgrouplayer.h"
19#include "moc_qgsgrouplayer.cpp"
20#include "qgsmaplayerfactory.h"
21#include "qgspainting.h"
24#include "qgsmaplayerref.h"
25#include "qgspainteffect.h"
27#include "qgsapplication.h"
28#include "qgsmaplayerutils.h"
29#include "qgsthreadingutils.h"
30
31QgsGroupLayer::QgsGroupLayer( const QString &name, const LayerOptions &options )
32 : QgsMapLayer( Qgis::LayerType::Group, name )
33 , mTransformContext( options.transformContext )
34{
35 mShouldValidateCrs = false;
36 mValid = true;
37
38 mPaintEffect.reset( QgsPaintEffectRegistry::defaultStack() );
39 mPaintEffect->setEnabled( false );
40
42 providerOptions.transformContext = options.transformContext;
43 mDataProvider = new QgsGroupLayerDataProvider( providerOptions, Qgis::DataProviderReadFlags() );
44}
45
47{
48 emit willBeDeleted();
49 delete mDataProvider;
50}
51
53{
55
56 const QgsGroupLayer::LayerOptions options( mTransformContext );
57 std::unique_ptr< QgsGroupLayer > layer = std::make_unique< QgsGroupLayer >( name(), options );
58 QgsMapLayer::clone( layer.get() );
59 layer->setChildLayers( _qgis_listRefToRaw( mChildren ) );
60 layer->setPaintEffect( mPaintEffect ? mPaintEffect->clone() : nullptr );
61 return layer.release();
62}
63
70
77
79{
81
82 if ( mDataProvider )
83 mDataProvider->setTransformContext( context );
84
85 mTransformContext = context;
87}
88
89bool QgsGroupLayer::readXml( const QDomNode &layerNode, QgsReadWriteContext &context )
90{
92
94 {
95 return false;
96 }
97
98 const QList< QgsMapLayer * > currentLayers = _qgis_listRefToRaw( mChildren );
99 for ( QgsMapLayer *layer : currentLayers )
100 {
102 }
103
104 mChildren.clear();
105 const QDomNodeList childLayersElements = layerNode.toElement().elementsByTagName( QStringLiteral( "childLayers" ) );
106 const QDomNodeList children = childLayersElements.at( 0 ).childNodes();
107 for ( int i = 0; i < children.size(); ++i )
108 {
109 const QDomElement childElement = children.at( i ).toElement();
110 const QString id = childElement.attribute( QStringLiteral( "layerid" ) );
111 mChildren.append( QgsMapLayerRef( id ) );
112 }
114
115 QString errorMsg;
116 readSymbology( layerNode, errorMsg, context );
117
119
120 return mValid;
121}
122
123bool QgsGroupLayer::writeXml( QDomNode &layer_node, QDomDocument &doc, const QgsReadWriteContext &context ) const
124{
126
127 // first get the layer element so that we can append the type attribute
128 QDomElement mapLayerNode = layer_node.toElement();
129
130 if ( mapLayerNode.isNull() )
131 {
132 QgsDebugMsgLevel( QStringLiteral( "can't find maplayer node" ), 2 );
133 return false;
134 }
135
136 mapLayerNode.setAttribute( QStringLiteral( "type" ), QgsMapLayerFactory::typeToString( Qgis::LayerType::Group ) );
137
138 QDomElement childLayersElement = doc.createElement( QStringLiteral( "childLayers" ) );
139 for ( auto it = mChildren.constBegin(); it != mChildren.constEnd(); ++it )
140 {
141 QDomElement childElement = doc.createElement( QStringLiteral( "child" ) );
142 childElement.setAttribute( QStringLiteral( "layerid" ), it->layerId );
143 childLayersElement.appendChild( childElement );
144 }
145 mapLayerNode.appendChild( childLayersElement );
146
147 // renderer specific settings
148 QString errorMsg;
149 return writeSymbology( layer_node, doc, errorMsg, context );
150}
151
152bool QgsGroupLayer::writeSymbology( QDomNode &node, QDomDocument &doc, QString &, const QgsReadWriteContext &, QgsMapLayer::StyleCategories categories ) const
153{
155
156 // add the layer opacity
157 if ( categories.testFlag( Rendering ) )
158 {
159 QDomElement layerOpacityElem = doc.createElement( QStringLiteral( "layerOpacity" ) );
160 const QDomText layerOpacityText = doc.createTextNode( QString::number( opacity() ) );
161 layerOpacityElem.appendChild( layerOpacityText );
162 node.appendChild( layerOpacityElem );
163
164 if ( mPaintEffect && !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect.get() ) )
165 {
166 QDomElement paintEffectElement = doc.createElement( QStringLiteral( "paintEffect" ) );
167 mPaintEffect->saveProperties( doc, paintEffectElement );
168 node.appendChild( paintEffectElement );
169 }
170 }
171
172 if ( categories.testFlag( Symbology ) )
173 {
174 // add the blend mode field
175 QDomElement blendModeElem = doc.createElement( QStringLiteral( "blendMode" ) );
176 const QDomText blendModeText = doc.createTextNode( QString::number( static_cast< int >( QgsPainting::getBlendModeEnum( blendMode() ) ) ) );
177 blendModeElem.appendChild( blendModeText );
178 node.appendChild( blendModeElem );
179 }
180
181 return true;
182}
183
184bool QgsGroupLayer::readSymbology( const QDomNode &node, QString &, QgsReadWriteContext &, QgsMapLayer::StyleCategories categories )
185{
187
188 if ( categories.testFlag( Rendering ) )
189 {
190 const QDomNode layerOpacityNode = node.namedItem( QStringLiteral( "layerOpacity" ) );
191 if ( !layerOpacityNode.isNull() )
192 {
193 const QDomElement e = layerOpacityNode.toElement();
194 setOpacity( e.text().toDouble() );
195 }
196
197 //restore layer effect
198 const QDomElement effectElem = node.namedItem( QStringLiteral( "paintEffect" ) ).toElement();
199 if ( !effectElem.isNull() )
200 {
201 const QDomElement effectPropertiesElem = effectElem.firstChildElement( QStringLiteral( "effect" ) ).toElement();
202 mPaintEffect.reset( QgsApplication::paintEffectRegistry()->createEffect( effectPropertiesElem ) );
203 }
204 else
205 {
206 mPaintEffect.reset( QgsPaintEffectRegistry::defaultStack() );
207 mPaintEffect->setEnabled( false );
208 }
209 }
210
211 if ( categories.testFlag( Symbology ) )
212 {
213 // get and set the blend mode if it exists
214 const QDomNode blendModeNode = node.namedItem( QStringLiteral( "blendMode" ) );
215 if ( !blendModeNode.isNull() )
216 {
217 const QDomElement e = blendModeNode.toElement();
218 setBlendMode( QgsPainting::getCompositionMode( static_cast< Qgis::BlendMode >( e.text().toInt() ) ) );
219 }
220 }
221
222 return true;
223}
224
231
233{
235
236 return mDataProvider;
237}
238
240{
242
243 QString metadata = QStringLiteral( "<html>\n<body>\n<h1>" ) + tr( "General" ) + QStringLiteral( "</h1>\n<hr>\n" ) + QStringLiteral( "<table class=\"list-view\">\n" );
244
245 metadata += QStringLiteral( "<tr><td class=\"highlight\">" ) + tr( "Name" ) + QStringLiteral( "</td><td>" ) + name() + QStringLiteral( "</td></tr>\n" );
246
247 // Extent
248 metadata += QStringLiteral( "<tr><td class=\"highlight\">" ) + tr( "Extent" ) + QStringLiteral( "</td><td>" ) + extent().toString() + QStringLiteral( "</td></tr>\n" );
249
250
251 metadata += QLatin1String( "\n</body>\n</html>\n" );
252 return metadata;
253}
254
256{
258
260 for ( int i = 0; i < mChildren.size(); ++i )
261 {
262 mChildren[i].resolve( project );
263
264 if ( mChildren[i].layer )
265 {
266 connect( mChildren[i].layer, &QgsMapLayer::repaintRequested, this, &QgsMapLayer::triggerRepaint, Qt::UniqueConnection );
267
268 // group layer inherits first valid child layer's crs
269 if ( !crs().isValid() )
270 {
271 setCrs( mChildren[i].layer->crs() );
272 mDataProvider->setCrs( crs() );
273 }
274 }
275 }
277}
278
279void QgsGroupLayer::setChildLayers( const QList< QgsMapLayer * > &layers )
280{
282
283 const QList< QgsMapLayer * > currentLayers = _qgis_listRefToRaw( mChildren );
284 for ( QgsMapLayer *layer : layers )
285 {
286 if ( !currentLayers.contains( layer ) )
287 {
288 connect( layer, &QgsMapLayer::repaintRequested, this, &QgsMapLayer::triggerRepaint, Qt::UniqueConnection );
289 if ( layer->blendMode() == QPainter::CompositionMode_SourceOver && layer->customProperty( QStringLiteral( "_prevGroupBlendMode" ) ).isValid() )
290 {
291 // try to restore previous group blend mode
292 layer->setBlendMode( static_cast< QPainter::CompositionMode >( layer->customProperty( QStringLiteral( "_prevGroupBlendMode" ) ).toInt() ) );
293 }
294 }
295 }
296 for ( QgsMapLayer *layer : currentLayers )
297 {
298 if ( layer && !layers.contains( layer ) )
299 {
300 // layer removed from group
302
303 const QPainter::CompositionMode groupBlendMode = layer->blendMode();
305 {
306 layer->setBlendMode( QPainter::CompositionMode_SourceOver );
307 layer->setCustomProperty( QStringLiteral( "_prevGroupBlendMode" ), static_cast< int >( groupBlendMode ) );
308 }
309 else
310 {
311 layer->removeCustomProperty( QStringLiteral( "_prevGroupBlendMode" ) );
312 }
313 }
314 }
315 mChildren = _qgis_listRawToRef( layers );
316
317 // group layer inherits first valid child layer's crs
318 for ( const QgsMapLayer *layer : layers )
319 {
320 if ( layer->isValid() && layer->crs().isValid( ) )
321 {
322 setCrs( layer->crs() );
323 mDataProvider->setCrs( crs() );
324 break;
325 }
326 }
327
329}
330
331QList< QgsMapLayer * > QgsGroupLayer::childLayers() const
332{
334
335 return _qgis_listRefToRaw( mChildren );
336}
337
339{
341
342 return mPaintEffect.get();
343}
344
346{
348
349 mPaintEffect.reset( effect );
350}
351
353{
354 for ( const QgsMapLayerRef &child : std::as_const( mChildren ) )
355 {
356 if ( child.get() && QgsPainting::isClippingMode( QgsPainting::getBlendModeEnum( child->blendMode() ) ) )
357 {
358 child->setBlendMode( QPainter::CompositionMode_SourceOver );
359 }
360 }
361}
362
363//
364// QgsGroupLayerDataProvider
365//
367QgsGroupLayerDataProvider::QgsGroupLayerDataProvider(
368 const ProviderOptions &options,
370 : QgsDataProvider( QString(), options, flags )
371{}
372
373void QgsGroupLayerDataProvider::setCrs( const QgsCoordinateReferenceSystem &crs )
374{
376
377 mCrs = crs;
378}
379
380QgsCoordinateReferenceSystem QgsGroupLayerDataProvider::crs() const
381{
383
384 return mCrs;
385}
386
387QString QgsGroupLayerDataProvider::name() const
388{
390
391 return QStringLiteral( "annotation" );
392}
393
394QString QgsGroupLayerDataProvider::description() const
395{
397
398 return QString();
399}
400
401QgsRectangle QgsGroupLayerDataProvider::extent() const
402{
404
405 return QgsRectangle();
406}
407
408bool QgsGroupLayerDataProvider::isValid() const
409{
411
412 return true;
413}
415
The Qgis class provides global constants for use throughout the application.
Definition qgis.h:54
BlendMode
Blending modes defining the available composition modes that can be used when painting.
Definition qgis.h:4594
QFlags< DataProviderReadFlag > DataProviderReadFlags
Flags which control data provider construction.
Definition qgis.h:450
@ Group
Composite group layer. Added in QGIS 3.24.
static QgsPaintEffectRegistry * paintEffectRegistry()
Returns the application's paint effect registry, used for managing paint effects.
This class represents a coordinate reference system (CRS).
Contains information about the context in which a coordinate transform is executed.
Abstract base class for spatial data provider implementations.
Implementation of threaded rendering for group layers.
A map layer which consists of a set of child layers, where all component layers are rendered as a sin...
void setPaintEffect(QgsPaintEffect *effect)
Sets the current paint effect for the renderer.
void resolveReferences(QgsProject *project) override
Resolve references to other layers (kept as layer IDs after reading XML) into layer objects.
bool readSymbology(const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories) override
Read the symbology for the current layer from the DOM node supplied.
QgsGroupLayer(const QString &name, const QgsGroupLayer::LayerOptions &options)
Constructor for a new QgsGroupLayer with the specified layer name.
void prepareLayersForRemovalFromGroup()
Prepares all child layers in the group prior to removal from the group.
QgsPaintEffect * paintEffect() const
Returns the current paint effect for the group layer.
QgsGroupLayer * clone() const override
Returns a new instance equivalent to this one except for the id which is still unique.
QList< QgsMapLayer * > childLayers() const
Returns the child layers contained by the group.
~QgsGroupLayer() override
QgsMapLayerRenderer * createMapRenderer(QgsRenderContext &rendererContext) override
Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context.
QgsDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
void setChildLayers(const QList< QgsMapLayer * > &layers)
Sets the child layers contained by the group.
bool writeXml(QDomNode &layer_node, QDomDocument &doc, const QgsReadWriteContext &context) const override
Called by writeLayerXML(), used by children to write state specific to them to project files.
void setTransformContext(const QgsCoordinateTransformContext &context) override
Sets the coordinate transform context to transformContext.
bool readXml(const QDomNode &layerNode, QgsReadWriteContext &context) override
Called by readLayerXML(), used by children to read state specific to them from project files.
bool writeSymbology(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &, StyleCategories categories=AllStyleCategories) const override
Write the style for the layer into the document provided.
QString htmlMetadata() const override
Obtain a formatted HTML string containing assorted metadata for this layer.
QgsRectangle extent() const override
Returns the extent of the layer.
static QString typeToString(Qgis::LayerType type)
Converts a map layer type to a string value.
Base class for utility classes that encapsulate information necessary for rendering of map layers.
static QgsRectangle combinedExtent(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &transformContext)
Returns the combined extent of a list of layers.
Base class for all map layer types.
Definition qgsmaplayer.h:76
QString name
Definition qgsmaplayer.h:80
void setBlendMode(QPainter::CompositionMode blendMode)
Set the blending mode used for rendering a layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:83
void triggerRepaint(bool deferredUpdate=false)
Will advise the map canvas (and any other interested party) that this layer requires to be repainted.
QgsLayerMetadata metadata
Definition qgsmaplayer.h:82
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
virtual void setOpacity(double opacity)
Sets the opacity for the layer, where opacity is a value between 0 (totally transparent) and 1....
QFlags< StyleCategory > StyleCategories
void willBeDeleted()
Emitted in the destructor when the layer is about to be deleted, but it is still in a perfectly valid...
virtual QgsMapLayer * clone() const =0
Returns a new instance equivalent to this one except for the id which is still unique.
virtual void resolveReferences(QgsProject *project)
Resolve references to other layers (kept as layer IDs after reading XML) into layer objects.
@ FlagDontResolveLayers
Don't resolve layer paths or create data providers for layers.
QgsMapLayer::ReadFlags mReadFlags
Read flags. It's up to the subclass to respect these when restoring state from XML.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
QgsProject * project() const
Returns the parent project if this map layer is added to a project.
double opacity
Definition qgsmaplayer.h:88
bool mValid
Indicates if the layer is valid and can be drawn.
@ Symbology
Symbology.
@ Rendering
Rendering: scale visibility, simplify method, opacity.
void invalidateWgs84Extent()
Invalidates the WGS84 extent.
bool mShouldValidateCrs
true if the layer's CRS should be validated and invalid CRSes are not permitted.
void setCrs(const QgsCoordinateReferenceSystem &srs, bool emitSignal=true)
Sets layer's spatial reference system.
static QgsPaintEffect * defaultStack()
Returns a new effect stack consisting of a sensible selection of default effects.
static bool isDefaultStack(QgsPaintEffect *effect)
Tests whether a paint effect matches the default effects stack.
Base class for visual effects which can be applied to QPicture drawings.
static Qgis::BlendMode getBlendModeEnum(QPainter::CompositionMode blendMode)
Returns a Qgis::BlendMode corresponding to a QPainter::CompositionMode.
static bool isClippingMode(Qgis::BlendMode mode)
Returns true if mode is a clipping blend mode.
static QPainter::CompositionMode getCompositionMode(Qgis::BlendMode blendMode)
Returns a QPainter::CompositionMode corresponding to a Qgis::BlendMode.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:107
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
Contains information about the context of a rendering operation.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
_LayerRef< QgsMapLayer > QgsMapLayerRef
#define QGIS_PROTECT_QOBJECT_THREAD_ACCESS
const QgsCoordinateReferenceSystem & crs
Setting options for creating vector data providers.
QgsCoordinateTransformContext transformContext
Coordinate transform context.
Setting options for loading group layers.
QgsCoordinateTransformContext transformContext
Coordinate transform context.