QGIS API Documentation  3.18.1-Zürich (202f1bf7e5)
qgslayoutitemattributetable.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgslayoutitemattributetable.cpp
3  -------------------------------
4  begin : November 2017
5  copyright : (C) 2017 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 
19 #include "qgslayout.h"
20 #include "qgslayouttablecolumn.h"
21 #include "qgslayoutitemmap.h"
22 #include "qgslayoututils.h"
23 #include "qgsfeatureiterator.h"
24 #include "qgsvectorlayer.h"
25 #include "qgslayoutframe.h"
26 #include "qgsproject.h"
27 #include "qgsrelationmanager.h"
28 #include "qgsgeometry.h"
29 #include "qgsexception.h"
30 #include "qgsmapsettings.h"
32 #include "qgsexpressionnodeimpl.h"
33 #include "qgsgeometryengine.h"
34 #include "qgsconditionalstyle.h"
35 
36 //
37 // QgsLayoutItemAttributeTable
38 //
39 
41  : QgsLayoutTable( layout )
42 {
43  if ( mLayout )
44  {
45  connect( mLayout->project(), static_cast < void ( QgsProject::* )( const QString & ) >( &QgsProject::layerWillBeRemoved ), this, &QgsLayoutItemAttributeTable::removeLayer );
46 
47  //coverage layer change = regenerate columns
48  connect( &mLayout->reportContext(), &QgsLayoutReportContext::layerChanged, this, &QgsLayoutItemAttributeTable::atlasLayerChanged );
49  }
51 }
52 
54 {
56 }
57 
59 {
60  return QgsApplication::getThemeIcon( QStringLiteral( "/mLayoutItemTable.svg" ) );
61 }
62 
64 {
65  return new QgsLayoutItemAttributeTable( layout );
66 }
67 
69 {
70  return tr( "<Attribute table frame>" );
71 }
72 
74 {
75  if ( layer == mVectorLayer.get() )
76  {
77  //no change
78  return;
79  }
80 
81  QgsVectorLayer *prevLayer = sourceLayer();
82  mVectorLayer.setLayer( layer );
83 
84  if ( mSource == QgsLayoutItemAttributeTable::LayerAttributes && layer != prevLayer )
85  {
86  if ( prevLayer )
87  {
88  //disconnect from previous layer
89  disconnect( prevLayer, &QgsVectorLayer::layerModified, this, &QgsLayoutTable::refreshAttributes );
90  }
91 
92  //rebuild column list to match all columns from layer
93  resetColumns();
94 
95  //listen for modifications to layer and refresh table when they occur
96  connect( mVectorLayer.get(), &QgsVectorLayer::layerModified, this, &QgsLayoutTable::refreshAttributes );
97  }
98 
100  emit changed();
101 }
102 
103 void QgsLayoutItemAttributeTable::setRelationId( const QString &relationId )
104 {
105  if ( relationId == mRelationId )
106  {
107  //no change
108  return;
109  }
110 
111  QgsVectorLayer *prevLayer = sourceLayer();
112  mRelationId = relationId;
113  QgsRelation relation = mLayout->project()->relationManager()->relation( mRelationId );
114  QgsVectorLayer *newLayer = relation.referencingLayer();
115 
116  if ( mSource == QgsLayoutItemAttributeTable::RelationChildren && newLayer != prevLayer )
117  {
118  if ( prevLayer )
119  {
120  //disconnect from previous layer
121  disconnect( prevLayer, &QgsVectorLayer::layerModified, this, &QgsLayoutTable::refreshAttributes );
122  }
123 
124  //rebuild column list to match all columns from layer
125  resetColumns();
126 
127  //listen for modifications to layer and refresh table when they occur
129  }
130 
132  emit changed();
133 }
134 
135 void QgsLayoutItemAttributeTable::atlasLayerChanged( QgsVectorLayer *layer )
136 {
137  if ( mSource != QgsLayoutItemAttributeTable::AtlasFeature || layer == mCurrentAtlasLayer )
138  {
139  //nothing to do
140  return;
141  }
142 
143  //atlas feature mode, atlas layer changed, so we need to reset columns
144  if ( mCurrentAtlasLayer )
145  {
146  //disconnect from previous layer
147  disconnect( mCurrentAtlasLayer, &QgsVectorLayer::layerModified, this, &QgsLayoutTable::refreshAttributes );
148  }
149 
150  const bool mustRebuildColumns = static_cast< bool >( mCurrentAtlasLayer ) || mColumns.empty();
151  mCurrentAtlasLayer = layer;
152 
153  if ( mustRebuildColumns )
154  {
155  //rebuild column list to match all columns from layer
156  resetColumns();
157  }
158 
160 
161  //listen for modifications to layer and refresh table when they occur
163 }
164 
166 {
168  if ( !source )
169  {
170  return;
171  }
172 
173  //remove existing columns
174  mColumns.clear();
175  mSortColumns.clear();
176 
177  //rebuild columns list from vector layer fields
178  int idx = 0;
179  const QgsFields sourceFields = source->fields();
180 
181  for ( const auto &field : sourceFields )
182  {
183  QString currentAlias = source->attributeDisplayName( idx );
185  col.setAttribute( field.name() );
186  col.setHeading( currentAlias );
187  mColumns.append( col );
188  idx++;
189  }
190 }
191 
192 void QgsLayoutItemAttributeTable::disconnectCurrentMap()
193 {
194  if ( !mMap )
195  {
196  return;
197  }
198 
201  disconnect( mMap, &QObject::destroyed, this, &QgsLayoutItemAttributeTable::disconnectCurrentMap );
202  mMap = nullptr;
203 }
204 
206 {
207  return mUseConditionalStyling;
208 }
209 
211 {
212  if ( useConditionalStyling == mUseConditionalStyling )
213  {
214  return;
215  }
216 
217  mUseConditionalStyling = useConditionalStyling;
219  emit changed();
220 }
221 
223 {
224  if ( map == mMap )
225  {
226  //no change
227  return;
228  }
229  disconnectCurrentMap();
230 
231  mMap = map;
232  if ( mMap )
233  {
234  //listen out for extent changes in linked map
237  connect( mMap, &QObject::destroyed, this, &QgsLayoutItemAttributeTable::disconnectCurrentMap );
238  }
240  emit changed();
241 }
242 
244 {
245  if ( features == mMaximumNumberOfFeatures )
246  {
247  return;
248  }
249 
250  mMaximumNumberOfFeatures = features;
252  emit changed();
253 }
254 
256 {
257  if ( uniqueOnly == mShowUniqueRowsOnly )
258  {
259  return;
260  }
261 
262  mShowUniqueRowsOnly = uniqueOnly;
264  emit changed();
265 }
266 
268 {
269  if ( visibleOnly == mShowOnlyVisibleFeatures )
270  {
271  return;
272  }
273 
274  mShowOnlyVisibleFeatures = visibleOnly;
276  emit changed();
277 }
278 
280 {
281  if ( filterToAtlas == mFilterToAtlasIntersection )
282  {
283  return;
284  }
285 
286  mFilterToAtlasIntersection = filterToAtlas;
288  emit changed();
289 }
290 
292 {
293  if ( filter == mFilterFeatures )
294  {
295  return;
296  }
297 
298  mFilterFeatures = filter;
300  emit changed();
301 }
302 
303 void QgsLayoutItemAttributeTable::setFeatureFilter( const QString &expression )
304 {
305  if ( expression == mFeatureFilter )
306  {
307  return;
308  }
309 
310  mFeatureFilter = expression;
312  emit changed();
313 }
314 
315 void QgsLayoutItemAttributeTable::setDisplayedFields( const QStringList &fields, bool refresh )
316 {
318  if ( !source )
319  {
320  return;
321  }
322 
323  //rebuild columns list, taking only fields contained in supplied list
324  mColumns.clear();
325 
326  const QgsFields layerFields = source->fields();
327 
328  if ( !fields.isEmpty() )
329  {
330  for ( const QString &field : fields )
331  {
332  int attrIdx = layerFields.lookupField( field );
333  if ( attrIdx < 0 )
334  {
335  continue;
336  }
337  QString currentAlias = source->attributeDisplayName( attrIdx );
339  col.setAttribute( layerFields.at( attrIdx ).name() );
340  col.setHeading( currentAlias );
341  mColumns.append( col );
342  }
343  }
344  else
345  {
346  //resetting, so add all attributes to columns
347  int idx = 0;
348  for ( const QgsField &field : layerFields )
349  {
350  QString currentAlias = source->attributeDisplayName( idx );
352  col.setAttribute( field.name() );
353  col.setHeading( currentAlias );
354  mColumns.append( col );
355  idx++;
356  }
357  }
358 
359  if ( refresh )
360  {
362  }
363 }
364 
365 void QgsLayoutItemAttributeTable::restoreFieldAliasMap( const QMap<int, QString> &map )
366 {
368  if ( !source )
369  {
370  return;
371  }
372 
373  for ( int i = 0; i < mColumns.count(); i++ )
374  {
375  int attrIdx = source->fields().lookupField( mColumns[i].attribute() );
376  if ( map.contains( attrIdx ) )
377  {
378  mColumns[i].setHeading( map.value( attrIdx ) );
379  }
380  else
381  {
382  mColumns[i].setHeading( source->attributeDisplayName( attrIdx ) );
383  }
384  }
385 }
386 
388 {
389  contents.clear();
390 
391  QgsVectorLayer *layer = sourceLayer();
392  if ( !layer )
393  {
394  //no source layer
395  return false;
396  }
397 
398  const QgsConditionalLayerStyles *conditionalStyles = layer->conditionalStyles();
399 
401  context.setFields( layer->fields() );
402 
403  QgsFeatureRequest req;
404  req.setExpressionContext( context );
405 
406  //prepare filter expression
407  std::unique_ptr<QgsExpression> filterExpression;
408  bool activeFilter = false;
409  if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
410  {
411  filterExpression = qgis::make_unique< QgsExpression >( mFeatureFilter );
412  if ( !filterExpression->hasParserError() )
413  {
414  activeFilter = true;
415  req.setFilterExpression( mFeatureFilter );
416  }
417  }
418 
419 #ifdef HAVE_SERVER_PYTHON_PLUGINS
420  if ( mLayout->renderContext().featureFilterProvider() )
421  {
422  mLayout->renderContext().featureFilterProvider()->filterFeatures( layer, req );
423  }
424 #endif
425 
426  QgsRectangle selectionRect;
427  QgsGeometry visibleRegion;
428  std::unique_ptr< QgsGeometryEngine > visibleMapEngine;
429  if ( mMap && mShowOnlyVisibleFeatures )
430  {
431  visibleRegion = QgsGeometry::fromQPolygonF( mMap->visibleExtentPolygon() );
432  selectionRect = visibleRegion.boundingBox();
433  //transform back to layer CRS
434  QgsCoordinateTransform coordTransform( layer->crs(), mMap->crs(), mLayout->project() );
435  try
436  {
437  selectionRect = coordTransform.transformBoundingBox( selectionRect, QgsCoordinateTransform::ReverseTransform );
438  visibleRegion.transform( coordTransform, QgsCoordinateTransform::ReverseTransform );
439  }
440  catch ( QgsCsException &cse )
441  {
442  Q_UNUSED( cse )
443  return false;
444  }
445  visibleMapEngine.reset( QgsGeometry::createGeometryEngine( visibleRegion.constGet() ) );
446  visibleMapEngine->prepareGeometry();
447  }
448 
449  QgsGeometry atlasGeometry;
450  std::unique_ptr< QgsGeometryEngine > atlasGeometryEngine;
451  if ( mFilterToAtlasIntersection )
452  {
453  atlasGeometry = mLayout->reportContext().currentGeometry( layer->crs() );
454  if ( !atlasGeometry.isNull() )
455  {
456  if ( selectionRect.isNull() )
457  {
458  selectionRect = atlasGeometry.boundingBox();
459  }
460  else
461  {
462  selectionRect = selectionRect.intersect( atlasGeometry.boundingBox() );
463  }
464 
465  atlasGeometryEngine.reset( QgsGeometry::createGeometryEngine( atlasGeometry.constGet() ) );
466  atlasGeometryEngine->prepareGeometry();
467  }
468  }
469 
471  {
472  QgsRelation relation = mLayout->project()->relationManager()->relation( mRelationId );
473  QgsFeature atlasFeature = mLayout->reportContext().feature();
474  req = relation.getRelatedFeaturesRequest( atlasFeature );
475  }
476 
477  if ( !selectionRect.isEmpty() )
478  req.setFilterRect( selectionRect );
479 
480  req.setFlags( mShowOnlyVisibleFeatures ? QgsFeatureRequest::ExactIntersect : QgsFeatureRequest::NoFlags );
481 
483  {
484  //source mode is current atlas feature
485  QgsFeature atlasFeature = mLayout->reportContext().feature();
486  req.setFilterFid( atlasFeature.id() );
487  }
488 
489  for ( const QgsLayoutTableColumn &column : qgis::as_const( mSortColumns ) )
490  {
491  req.addOrderBy( column.attribute(), column.sortOrder() == Qt::AscendingOrder );
492  }
493 
494  QgsFeature f;
495  int counter = 0;
496  QgsFeatureIterator fit = layer->getFeatures( req );
497 
498  mConditionalStyles.clear();
499  mFeatures.clear();
500 
501  QVector< QVector< Cell > > tempContents;
502  QgsLayoutTableContents existingContents;
503 
504  while ( fit.nextFeature( f ) && counter < mMaximumNumberOfFeatures )
505  {
506  context.setFeature( f );
507  //check feature against filter
508  if ( activeFilter && filterExpression )
509  {
510  QVariant result = filterExpression->evaluate( &context );
511  // skip this feature if the filter evaluation is false
512  if ( !result.toBool() )
513  {
514  continue;
515  }
516  }
517 
518  // check against exact map bounds
519  if ( visibleMapEngine )
520  {
521  if ( !f.hasGeometry() )
522  continue;
523 
524  if ( !visibleMapEngine->intersects( f.geometry().constGet() ) )
525  continue;
526  }
527 
528  //check against atlas feature intersection
529  if ( mFilterToAtlasIntersection )
530  {
531  if ( !f.hasGeometry() || !atlasGeometryEngine )
532  {
533  continue;
534  }
535 
536  if ( !atlasGeometryEngine->intersects( f.geometry().constGet() ) )
537  continue;
538  }
539 
540  QgsConditionalStyle rowStyle;
541 
542  if ( mUseConditionalStyling )
543  {
544  const QList<QgsConditionalStyle> styles = QgsConditionalStyle::matchingConditionalStyles( conditionalStyles->rowStyles(), QVariant(), context );
545  rowStyle = QgsConditionalStyle::compressStyles( styles );
546  }
547 
548  // We need to build up two different lists here -- one is a pair of the cell contents along with the cell style.
549  // We need this one because we do a sorting step later, and we need to ensure that the cell styling is attached to the right row and sorted
550  // correctly when this occurs
551  // We also need a list of just the cell contents, so that we can do a quick check for row uniqueness (when the
552  // corresponding option is enabled)
553  QVector< Cell > currentRow;
554 #ifdef HAVE_SERVER_PYTHON_PLUGINS
555  mColumns = filteredColumns();
556 #endif
557  currentRow.reserve( mColumns.count() );
558  QgsLayoutTableRow rowContents;
559  rowContents.reserve( mColumns.count() );
560 
561  for ( const QgsLayoutTableColumn &column : qgis::as_const( mColumns ) )
562  {
563  int idx = layer->fields().lookupField( column.attribute() );
564 
565  QgsConditionalStyle style;
566 
567  if ( idx != -1 )
568  {
569  const QVariant val = f.attributes().at( idx );
570 
571  if ( mUseConditionalStyling )
572  {
573  QList<QgsConditionalStyle> styles = conditionalStyles->fieldStyles( layer->fields().at( idx ).name() );
574  styles = QgsConditionalStyle::matchingConditionalStyles( styles, val, context );
575  styles.insert( 0, rowStyle );
576  style = QgsConditionalStyle::compressStyles( styles );
577  }
578 
579  QVariant v = replaceWrapChar( val );
580  currentRow << Cell( v, style, f );
581  rowContents << v;
582  }
583  else
584  {
585  // Lets assume it's an expression
586  std::unique_ptr< QgsExpression > expression = qgis::make_unique< QgsExpression >( column.attribute() );
587  context.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), counter + 1, true ) );
588  expression->prepare( &context );
589  QVariant value = expression->evaluate( &context );
590 
591  currentRow << Cell( value, rowStyle, f );
592  rowContents << value;
593  }
594  }
595 
596  if ( mShowUniqueRowsOnly )
597  {
598  if ( contentsContainsRow( existingContents, rowContents ) )
599  continue;
600  }
601 
602  tempContents << currentRow;
603  existingContents << rowContents;
604  ++counter;
605  }
606 
607  // build final table contents
608  contents.reserve( tempContents.size() );
609  mConditionalStyles.reserve( tempContents.size() );
610  mFeatures.reserve( tempContents.size() );
611  for ( auto it = tempContents.constBegin(); it != tempContents.constEnd(); ++it )
612  {
613  QgsLayoutTableRow row;
614  QList< QgsConditionalStyle > rowStyles;
615  row.reserve( it->size() );
616  rowStyles.reserve( it->size() );
617 
618  for ( auto cellIt = it->constBegin(); cellIt != it->constEnd(); ++cellIt )
619  {
620  row << cellIt->content;
621  rowStyles << cellIt->style;
622  if ( cellIt == it->constBegin() )
623  mFeatures << cellIt->feature;
624  }
625  contents << row;
626  mConditionalStyles << rowStyles;
627  }
628 
630  return true;
631 }
632 
634 {
635  if ( row >= mConditionalStyles.size() )
636  return QgsConditionalStyle();
637 
638  return mConditionalStyles.at( row ).at( column );
639 }
640 
642 {
643  std::unique_ptr< QgsExpressionContextScope >scope( QgsLayoutTable::scopeForCell( row, column ) );
644  scope->setFeature( mFeatures.value( row ) );
645  scope->setFields( scope->feature().fields() );
646  return scope.release();
647 }
648 
650 {
652 
653  if ( mSource == LayerAttributes )
654  {
655  context.appendScope( QgsExpressionContextUtils::layerScope( mVectorLayer.get() ) );
656  }
657 
658  return context;
659 }
660 
662 {
664  if ( !mMap && !mMapUuid.isEmpty() && mLayout )
665  {
666  mMap = qobject_cast< QgsLayoutItemMap *>( mLayout->itemByUuid( mMapUuid, true ) );
667  if ( mMap )
668  {
669  //if we have found a valid map item, listen out to extent changes on it and refresh the table
672  }
673  }
674 }
675 
677 {
679 
682  {
683  mDataDefinedVectorLayer = nullptr;
684 
685  QString currentLayerIdentifier;
686  if ( QgsVectorLayer *currentLayer = mVectorLayer.get() )
687  currentLayerIdentifier = currentLayer->id();
688 
689  const QString layerIdentifier = mDataDefinedProperties.valueAsString( QgsLayoutObject::AttributeTableSourceLayer, context, currentLayerIdentifier );
690  QgsVectorLayer *ddLayer = qobject_cast< QgsVectorLayer * >( QgsLayoutUtils::mapLayerFromString( layerIdentifier, mLayout->project() ) );
691  if ( ddLayer )
692  mDataDefinedVectorLayer = ddLayer;
693  }
694 
696 }
697 
698 QVariant QgsLayoutItemAttributeTable::replaceWrapChar( const QVariant &variant ) const
699 {
700  //avoid converting variants to string if not required (try to maintain original type for sorting)
701  if ( mWrapString.isEmpty() || !variant.toString().contains( mWrapString ) )
702  return variant;
703 
704  QString replaced = variant.toString();
705  replaced.replace( mWrapString, QLatin1String( "\n" ) );
706  return replaced;
707 }
708 
709 #ifdef HAVE_SERVER_PYTHON_PLUGINS
710 QgsLayoutTableColumns QgsLayoutItemAttributeTable::filteredColumns()
711 {
712 
713  QgsLayoutTableColumns allowedColumns { mColumns };
714 
715  // Filter columns
716  if ( mLayout->renderContext().featureFilterProvider() )
717  {
718 
720 
721  if ( ! source )
722  {
723  return allowedColumns;
724  }
725 
726  QHash<const QString, QSet<QString>> columnAttributesMap;
727  QSet<QString> allowedAttributes;
728 
729  for ( const auto &c : qgis::as_const( allowedColumns ) )
730  {
731  if ( ! c.attribute().isEmpty() && ! columnAttributesMap.contains( c.attribute() ) )
732  {
733  columnAttributesMap[ c.attribute() ] = QSet<QString>();
734  const QgsExpression columnExp { c.attribute() };
735  const auto constRefs { columnExp.findNodes<QgsExpressionNodeColumnRef>() };
736  for ( const auto &cref : constRefs )
737  {
738  columnAttributesMap[ c.attribute() ].insert( cref->name() );
739  allowedAttributes.insert( cref->name() );
740  }
741  }
742  }
743 
744  const QStringList filteredAttributes { layout()->renderContext().featureFilterProvider()->layerAttributes( source, allowedAttributes.values() ) };
745 #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
746  const QSet<QString> filteredAttributesSet( filteredAttributes.constBegin(), filteredAttributes.constEnd() );
747 #else
748  const QSet<QString> filteredAttributesSet { filteredAttributes.toSet() };
749 #endif
750  if ( filteredAttributesSet != allowedAttributes )
751  {
752  const auto forbidden { allowedAttributes.subtract( filteredAttributesSet ) };
753  allowedColumns.erase( std::remove_if( allowedColumns.begin(), allowedColumns.end(), [ &columnAttributesMap, &forbidden ]( QgsLayoutTableColumn & c ) -> bool
754  {
755  for ( const auto &f : qgis::as_const( forbidden ) )
756  {
757  if ( columnAttributesMap[ c.attribute() ].contains( f ) )
758  {
759  return true;
760  }
761  }
762  return false;
763  } ), allowedColumns.end() );
764 
765  }
766  }
767 
768  return allowedColumns;
769 }
770 #endif
771 
773 {
774  switch ( mSource )
775  {
777  return mLayout->reportContext().layer();
779  {
780  if ( mDataDefinedVectorLayer )
781  return mDataDefinedVectorLayer;
782  else
783  return mVectorLayer.get();
784  }
786  {
787  QgsRelation relation = mLayout->project()->relationManager()->relation( mRelationId );
788  return relation.referencingLayer();
789  }
790  }
791  return nullptr;
792 }
793 
794 void QgsLayoutItemAttributeTable::removeLayer( const QString &layerId )
795 {
796  if ( mVectorLayer && mSource == QgsLayoutItemAttributeTable::LayerAttributes )
797  {
798  if ( layerId == mVectorLayer->id() )
799  {
800  mVectorLayer.setLayer( nullptr );
801  //remove existing columns
802  mColumns.clear();
803  }
804  }
805 }
806 
807 void QgsLayoutItemAttributeTable::setWrapString( const QString &wrapString )
808 {
809  if ( wrapString == mWrapString )
810  {
811  return;
812  }
813 
814  mWrapString = wrapString;
816  emit changed();
817 }
818 
819 bool QgsLayoutItemAttributeTable::writePropertiesToElement( QDomElement &tableElem, QDomDocument &doc, const QgsReadWriteContext &context ) const
820 {
821  if ( !QgsLayoutTable::writePropertiesToElement( tableElem, doc, context ) )
822  return false;
823 
824  tableElem.setAttribute( QStringLiteral( "source" ), QString::number( static_cast< int >( mSource ) ) );
825  tableElem.setAttribute( QStringLiteral( "relationId" ), mRelationId );
826  tableElem.setAttribute( QStringLiteral( "showUniqueRowsOnly" ), mShowUniqueRowsOnly );
827  tableElem.setAttribute( QStringLiteral( "showOnlyVisibleFeatures" ), mShowOnlyVisibleFeatures );
828  tableElem.setAttribute( QStringLiteral( "filterToAtlasIntersection" ), mFilterToAtlasIntersection );
829  tableElem.setAttribute( QStringLiteral( "maxFeatures" ), mMaximumNumberOfFeatures );
830  tableElem.setAttribute( QStringLiteral( "filterFeatures" ), mFilterFeatures ? QStringLiteral( "true" ) : QStringLiteral( "false" ) );
831  tableElem.setAttribute( QStringLiteral( "featureFilter" ), mFeatureFilter );
832  tableElem.setAttribute( QStringLiteral( "wrapString" ), mWrapString );
833  tableElem.setAttribute( QStringLiteral( "useConditionalStyling" ), mUseConditionalStyling );
834 
835  if ( mMap )
836  {
837  tableElem.setAttribute( QStringLiteral( "mapUuid" ), mMap->uuid() );
838  }
839 
840  if ( mVectorLayer )
841  {
842  tableElem.setAttribute( QStringLiteral( "vectorLayer" ), mVectorLayer.layerId );
843  tableElem.setAttribute( QStringLiteral( "vectorLayerName" ), mVectorLayer.name );
844  tableElem.setAttribute( QStringLiteral( "vectorLayerSource" ), mVectorLayer.source );
845  tableElem.setAttribute( QStringLiteral( "vectorLayerProvider" ), mVectorLayer.provider );
846  }
847  return true;
848 }
849 
850 bool QgsLayoutItemAttributeTable::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context )
851 {
852  if ( QgsVectorLayer *prevLayer = sourceLayer() )
853  {
854  //disconnect from previous layer
855  disconnect( prevLayer, &QgsVectorLayer::layerModified, this, &QgsLayoutTable::refreshAttributes );
856  }
857 
858  if ( !QgsLayoutTable::readPropertiesFromElement( itemElem, doc, context ) )
859  return false;
860 
861  mSource = QgsLayoutItemAttributeTable::ContentSource( itemElem.attribute( QStringLiteral( "source" ), QStringLiteral( "0" ) ).toInt() );
862  mRelationId = itemElem.attribute( QStringLiteral( "relationId" ), QString() );
863 
865  {
866  mCurrentAtlasLayer = mLayout->reportContext().layer();
867  }
868 
869  mShowUniqueRowsOnly = itemElem.attribute( QStringLiteral( "showUniqueRowsOnly" ), QStringLiteral( "0" ) ).toInt();
870  mShowOnlyVisibleFeatures = itemElem.attribute( QStringLiteral( "showOnlyVisibleFeatures" ), QStringLiteral( "1" ) ).toInt();
871  mFilterToAtlasIntersection = itemElem.attribute( QStringLiteral( "filterToAtlasIntersection" ), QStringLiteral( "0" ) ).toInt();
872  mFilterFeatures = itemElem.attribute( QStringLiteral( "filterFeatures" ), QStringLiteral( "false" ) ) == QLatin1String( "true" );
873  mFeatureFilter = itemElem.attribute( QStringLiteral( "featureFilter" ), QString() );
874  mMaximumNumberOfFeatures = itemElem.attribute( QStringLiteral( "maxFeatures" ), QStringLiteral( "5" ) ).toInt();
875  mWrapString = itemElem.attribute( QStringLiteral( "wrapString" ) );
876  mUseConditionalStyling = itemElem.attribute( QStringLiteral( "useConditionalStyling" ), QStringLiteral( "0" ) ).toInt();
877 
878  //map
879  mMapUuid = itemElem.attribute( QStringLiteral( "mapUuid" ) );
880  if ( mMap )
881  {
884  mMap = nullptr;
885  }
886  // setting new mMap occurs in finalizeRestoreFromXml
887 
888  //vector layer
889  QString layerId = itemElem.attribute( QStringLiteral( "vectorLayer" ) );
890  QString layerName = itemElem.attribute( QStringLiteral( "vectorLayerName" ) );
891  QString layerSource = itemElem.attribute( QStringLiteral( "vectorLayerSource" ) );
892  QString layerProvider = itemElem.attribute( QStringLiteral( "vectorLayerProvider" ) );
893  mVectorLayer = QgsVectorLayerRef( layerId, layerName, layerSource, layerProvider );
894  mVectorLayer.resolveWeakly( mLayout->project() );
895 
896  //connect to new layer
897  if ( QgsVectorLayer *newLayer = sourceLayer() )
899 
901 
902  emit changed();
903  return true;
904 }
905 
907 {
908  if ( source == mSource )
909  {
910  return;
911  }
912 
913  QgsVectorLayer *prevLayer = sourceLayer();
914  mSource = source;
915  QgsVectorLayer *newLayer = sourceLayer();
916 
917  if ( newLayer != prevLayer )
918  {
919  //disconnect from previous layer
920  if ( prevLayer )
921  {
922  disconnect( prevLayer, &QgsVectorLayer::layerModified, this, &QgsLayoutTable::refreshAttributes );
923  }
924 
925  //connect to new layer
928  {
929  mCurrentAtlasLayer = newLayer;
930  }
931 
932  //layer has changed as a result of the source change, so reset column list
933  resetColumns();
934  }
935 
937  emit changed();
938 }
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.
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
The QgsConditionalLayerStyles class holds conditional style information for a layer.
QgsConditionalStyles rowStyles() const
Returns a list of row styles associated with the layer.
QList< QgsConditionalStyle > fieldStyles(const QString &fieldName) const
Returns the conditional styles set for the field with matching fieldName.
Conditional styling for a rule.
static QgsConditionalStyle compressStyles(const QList< QgsConditionalStyle > &styles)
Compress a list of styles into a single style.
static QList< QgsConditionalStyle > matchingConditionalStyles(const QList< QgsConditionalStyle > &styles, const QVariant &value, QgsExpressionContext &context)
Find and return the matching styles for the value and feature.
Class for doing transforms between two map coordinate systems.
@ ReverseTransform
Transform from destination to source CRS.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, TransformDirection direction=ForwardTransform, bool handle180Crossover=false) const SIP_THROW(QgsCsException)
Transforms a rectangle from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:66
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QgsExpressionContextScope * lastScope()
Returns the last scope added to the context.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
An expression node which takes it value from a feature's field.
Class for parsing and evaluation of expressions (formerly called "search strings").
virtual QStringList layerAttributes(const QgsVectorLayer *layer, const QStringList &attributes) const =0
Returns the list of visible attribute names from a list of attributes names for the given layer.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & addOrderBy(const QString &expression, bool ascending=true)
Adds a new OrderByClause, appending it as the least important one.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
@ ExactIntersect
Use exact geometry intersection (slower) instead of bounding boxes.
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
QgsFeatureRequest & setFilterFid(QgsFeatureId fid)
Sets feature ID that should be fetched.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:56
QgsAttributes attributes
Definition: qgsfeature.h:65
QgsGeometry geometry
Definition: qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:204
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:51
QString name
Definition: qgsfield.h:60
Container of fields for a vector layer.
Definition: qgsfields.h:45
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
Definition: qgsfields.cpp:163
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
Definition: qgsfields.cpp:344
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
Q_GADGET bool isNull
Definition: qgsgeometry.h:126
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine.
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.
A layout table subclass that displays attributes from a vector layer.
void resetColumns()
Resets the attribute table's columns to match the vector layer's fields.
QString wrapString() const
Returns the string used to wrap the contents of the table cells by.
bool readPropertiesFromElement(const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context) override
Sets multiframe state from a DOM element.
ContentSource
Specifies the content source for the attribute table.
@ AtlasFeature
Table shows attributes from the current atlas feature.
@ RelationChildren
Table shows attributes from related child features.
@ LayerAttributes
Table shows attributes from features in a vector layer.
QgsVectorLayer * sourceLayer() const
Returns the source layer for the table, considering the table source mode.
void setDisplayedFields(const QStringList &fields, bool refresh=true)
Sets the attributes to display in the table.
void setUseConditionalStyling(bool enabled)
Sets whether the attribute table will be rendered using the conditional styling properties of the lin...
void setRelationId(const QString &id)
Sets the relation id from which to display child features.
void setMaximumNumberOfFeatures(int features)
Sets the maximum number of features shown by the table.
void setDisplayOnlyVisibleFeatures(bool visibleOnly)
Sets the attribute table to only show features which are visible in a map item.
void setFeatureFilter(const QString &expression)
Sets the expression used for filtering features in the table.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
void finalizeRestoreFromXml() override
Called after all pending items have been restored from XML.
bool useConditionalStyling() const
Returns true if the attribute table will be rendered using the conditional styling properties of the ...
ContentSource source() const
Returns the source for attributes shown in the table body.
int type() const override
Returns unique multiframe type id.
QgsConditionalStyle conditionalCellStyle(int row, int column) const override
Returns the conditional style to use for the cell at row, column.
void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties) override
Refreshes a data defined property for the multi frame by reevaluating the property's value and redraw...
QgsExpressionContextScope * scopeForCell(int row, int column) const override
Creates a new QgsExpressionContextScope for the cell at row, column.
void setFilterFeatures(bool filter)
Sets whether the feature filter is active for the attribute table.
void setUniqueRowsOnly(bool uniqueOnly)
Sets attribute table to only show unique rows.
QString relationId() const
Returns the relation id which the table displays child features from.
void setWrapString(const QString &wrapString)
Sets a string to wrap the contents of the table cells by.
QIcon icon() const override
Returns the item's icon.
void setMap(QgsLayoutItemMap *map)
Sets a layout map to use to limit the extent of features shown in the attribute table.
QgsLayoutItemMap * map() const
Returns the layout map whose extents are controlling the features shown in the table.
void setFilterToAtlasFeature(bool filterToAtlas)
Sets attribute table to only show features which intersect the current atlas feature.
QString displayName() const override
Returns the multiframe display name.
bool writePropertiesToElement(QDomElement &elem, QDomDocument &doc, const QgsReadWriteContext &context) const override
Stores multiframe state within an XML DOM element.
bool getTableContents(QgsLayoutTableContents &contents) override
Queries the attribute table's vector layer for attributes to show in the table.
QgsLayoutItemAttributeTable(QgsLayout *layout)
Constructor for QgsLayoutItemAttributeTable, attached to the specified layout.
static QgsLayoutItemAttributeTable * create(QgsLayout *layout)
Returns a new QgsLayoutItemAttributeTable for the specified parent layout.
void setVectorLayer(QgsVectorLayer *layer)
Sets the vector layer from which to display feature attributes.
void setSource(ContentSource source)
Sets the source for attributes to show in table body.
Layout graphical items for displaying a map.
void extentChanged()
Emitted when the map's extent changes.
void mapRotationChanged(double newRotation)
Emitted when the map's rotation changes.
QPolygonF visibleExtentPolygon() const
Returns a polygon representing the current visible map extent, considering map extents and rotation.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
@ LayoutAttributeTable
Attribute table.
virtual QString uuid() const
Returns the item identification string.
virtual void finalizeRestoreFromXml()
Called after all pending items have been restored from XML.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
virtual void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::AllProperties)
Refreshes a data defined property for the multi frame by reevaluating the property's value and redraw...
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.
@ AttributeTableSourceLayer
Attribute table source layer.
@ AllProperties
All properties for item.
QgsFeatureFilterProvider * featureFilterProvider() const
Returns the possibly NULL feature filter provider.
void layerChanged(QgsVectorLayer *layer)
Emitted when the context's layer is changed.
Stores properties of a column for a QgsLayoutTable.
void setAttribute(const QString &attribute)
Sets the attribute name or expression used for the column's values.
void setHeading(const QString &heading)
Sets the heading for a column, which is the value displayed in the column's header cell.
A class to display a table in the print layout, and allow the table to span over multiple frames.
virtual void refreshAttributes()
Refreshes the contents shown in the table by querying for new data.
void recalculateTableSize()
Recalculates and updates the size of the table and all table frames.
virtual QgsExpressionContextScope * scopeForCell(int row, int column) const
Creates a new QgsExpressionContextScope for the cell at row, column.
QgsLayoutTableContents & contents()
Returns the current contents of the table.
bool contentsContainsRow(const QgsLayoutTableContents &contents, const QgsLayoutTableRow &row) const
Checks whether a table contents contains a given row.
QgsLayoutTableColumns mColumns
Columns to show in table.
bool writePropertiesToElement(QDomElement &elem, QDomDocument &doc, const QgsReadWriteContext &context) const override
Stores multiframe state within an XML DOM element.
QgsLayoutTableSortColumns mSortColumns
Columns to sort the table.
bool readPropertiesFromElement(const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context) override
Sets multiframe state from a DOM element.
void refresh() override
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProject *project)
Resolves a string into a map layer from a given project.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
Definition: qgslayout.h:50
QgsLayoutRenderContext & renderContext()
Returns a reference to the layout's render context, which stores information relating to the current ...
Definition: qgslayout.cpp:359
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:91
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition: qgsproject.h:99
void layerWillBeRemoved(const QString &layerId)
Emitted when a layer is about to be removed from the registry.
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
Definition: qgsrectangle.h:42
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
Definition: qgsrectangle.h:447
bool isEmpty() const
Returns true if the rectangle is empty.
Definition: qgsrectangle.h:437
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
Definition: qgsrectangle.h:312
QgsVectorLayer * referencingLayer
Definition: qgsrelation.h:47
QgsFeatureRequest getRelatedFeaturesRequest(const QgsFeature &feature) const
Creates a request to return all the features on the referencing (child) layer which have a foreign ke...
Represents a vector layer which manages a vector based data sets.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
void layerModified()
Emitted when modifications has been done on layer.
QgsConditionalLayerStyles * conditionalStyles() const
Returns the conditional styles that are set for this layer.
QVector< QgsLayoutTableColumn > QgsLayoutTableColumns
List of column definitions for a QgsLayoutTable.
QVector< QgsLayoutTableRow > QgsLayoutTableContents
List of QgsLayoutTableRows, representing rows and column cell contents for a QgsLayoutTable.
QVector< QVariant > QgsLayoutTableRow
List of QVariants, representing a the contents of a single row in a QgsLayoutTable.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
const QgsField & field
Definition: qgsfield.h:472
_LayerRef< QgsVectorLayer > QgsVectorLayerRef
Single variable definition for use within a QgsExpressionContextScope.
QString source
Weak reference to layer public source.
QString name
Weak reference to layer name.
TYPE * get() const
Returns a pointer to the layer, or nullptr if the reference has not yet been matched to a layer.
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.
void setLayer(TYPE *l)
Sets the reference to point to a specified layer.
QString layerId
Original layer ID.