42 class CORE_EXPORT QgsLayoutAttributeTableCompare
49 QgsLayoutAttributeTableCompare() =
default;
50 bool operator()(
const QVector< QPair< QVariant, QgsConditionalStyle > > &m1,
const QVector< QPair< QVariant, QgsConditionalStyle > > &m2 )
52 return ( mAscending ?
qgsVariantLessThan( m1[mCurrentSortColumn].first, m2[mCurrentSortColumn].first )
59 void setSortColumn(
int column ) { mCurrentSortColumn = column; }
65 void setAscending(
bool ascending ) { mAscending = ascending; }
68 int mCurrentSortColumn = 0;
69 bool mAscending =
true;
108 return tr(
"<Attribute table frame>" );
113 if ( layer == mVectorLayer.
get() )
143 if ( relationId == mRelationId )
151 QgsRelation relation =
mLayout->project()->relationManager()->relation( mRelationId );
173 void QgsLayoutItemAttributeTable::atlasLayerChanged(
QgsVectorLayer *layer )
182 if ( mCurrentAtlasLayer )
188 const bool mustRebuildColumns =
static_cast< bool >( mCurrentAtlasLayer ) ||
mColumns.empty();
189 mCurrentAtlasLayer = layer;
191 if ( mustRebuildColumns )
218 for (
const auto &field : sourceFields )
221 std::unique_ptr< QgsLayoutTableColumn > col = qgis::make_unique< QgsLayoutTableColumn >();
222 col->setAttribute( field.name() );
223 col->setHeading( currentAlias );
229 void QgsLayoutItemAttributeTable::disconnectCurrentMap()
238 disconnect( mMap, &QObject::destroyed,
this, &QgsLayoutItemAttributeTable::disconnectCurrentMap );
244 return mUseConditionalStyling;
249 if ( useConditionalStyling == mUseConditionalStyling )
266 disconnectCurrentMap();
274 connect( mMap, &QObject::destroyed,
this, &QgsLayoutItemAttributeTable::disconnectCurrentMap );
282 if ( features == mMaximumNumberOfFeatures )
287 mMaximumNumberOfFeatures = features;
294 if ( uniqueOnly == mShowUniqueRowsOnly )
299 mShowUniqueRowsOnly = uniqueOnly;
306 if ( visibleOnly == mShowOnlyVisibleFeatures )
311 mShowOnlyVisibleFeatures = visibleOnly;
318 if ( filterToAtlas == mFilterToAtlasIntersection )
323 mFilterToAtlasIntersection = filterToAtlas;
330 if ( filter == mFilterFeatures )
335 mFilterFeatures = filter;
342 if ( expression == mFeatureFilter )
347 mFeatureFilter = expression;
366 if ( !fields.isEmpty() )
368 for (
const QString &field : fields )
375 std::unique_ptr< QgsLayoutTableColumn > col = qgis::make_unique< QgsLayoutTableColumn >();
376 col->setAttribute( layerFields.
at( attrIdx ).
name() );
377 col->setHeading( currentAlias );
385 for (
const QgsField &field : layerFields )
388 std::unique_ptr< QgsLayoutTableColumn > col = qgis::make_unique< QgsLayoutTableColumn >();
389 col->setAttribute( field.name() );
390 col->setHeading( currentAlias );
402 void QgsLayoutItemAttributeTable::restoreFieldAliasMap(
const QMap<int, QString> &
map )
413 if ( map.contains( attrIdx ) )
415 column->setHeading( map.value( attrIdx ) );
443 std::unique_ptr<QgsExpression> filterExpression;
444 bool activeFilter =
false;
445 if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
447 filterExpression = qgis::make_unique< QgsExpression >( mFeatureFilter );
448 if ( !filterExpression->hasParserError() )
458 std::unique_ptr< QgsGeometryEngine > visibleMapEngine;
459 if ( mMap && mShowOnlyVisibleFeatures )
479 visibleMapEngine->prepareGeometry();
483 std::unique_ptr< QgsGeometryEngine > atlasGeometryEngine;
484 if ( mFilterToAtlasIntersection )
486 atlasGeometry =
mLayout->reportContext().currentGeometry( layer->
crs() );
487 if ( !atlasGeometry.
isNull() )
489 if ( selectionRect.
isNull() )
499 atlasGeometryEngine->prepareGeometry();
505 QgsRelation relation =
mLayout->project()->relationManager()->relation( mRelationId );
510 if ( !selectionRect.
isEmpty() )
526 mConditionalStyles.clear();
528 QVector< QVector< QPair< QVariant, QgsConditionalStyle > > > tempContents;
531 while ( fit.
nextFeature( f ) && counter < mMaximumNumberOfFeatures )
535 if ( activeFilter && filterExpression )
537 QVariant result = filterExpression->evaluate( &context );
539 if ( !result.toBool() )
546 if ( visibleMapEngine )
556 if ( mFilterToAtlasIntersection )
569 if ( mUseConditionalStyling )
580 QVector< QPair< QVariant, QgsConditionalStyle > > currentRow;
581 currentRow.reserve(
mColumns.count() );
583 rowContents.reserve(
mColumns.count() );
593 const QVariant val = f.
attributes().at( idx );
595 if ( mUseConditionalStyling )
599 styles.insert( 0, rowStyle );
603 QVariant v = replaceWrapChar( val );
604 currentRow << qMakePair( v, style );
610 std::unique_ptr< QgsExpression > expression = qgis::make_unique< QgsExpression >( column->attribute() );
612 expression->prepare( &context );
613 QVariant value = expression->evaluate( &context );
615 currentRow << qMakePair( value, rowStyle );
616 rowContents << value;
620 if ( mShowUniqueRowsOnly )
626 tempContents << currentRow;
627 existingContents << rowContents;
632 QgsLayoutAttributeTableCompare
c;
634 for (
int i = sortColumns.size() - 1; i >= 0; --i )
636 c.setSortColumn( sortColumns.at( i ).first );
637 c.setAscending( sortColumns.at( i ).second );
638 std::stable_sort( tempContents.begin(), tempContents.end(),
c );
642 contents.reserve( tempContents.size() );
643 mConditionalStyles.reserve( tempContents.size() );
644 for (
auto it = tempContents.constBegin(); it != tempContents.constEnd(); ++it )
647 QList< QgsConditionalStyle > rowStyles;
648 row.reserve( it->size() );
649 rowStyles.reserve( it->size() );
651 for (
auto cellIt = it->constBegin(); cellIt != it->constEnd(); ++cellIt )
653 row << cellIt->first;
654 rowStyles << cellIt->second;
657 mConditionalStyles << rowStyles;
666 if ( row >= mConditionalStyles.size() )
669 return mConditionalStyles.at( row ).at( column );
687 if ( !mMap && !mMapUuid.isEmpty() &&
mLayout )
706 mDataDefinedVectorLayer =
nullptr;
708 QString currentLayerIdentifier;
710 currentLayerIdentifier = currentLayer->id();
715 mDataDefinedVectorLayer = ddLayer;
721 QVariant QgsLayoutItemAttributeTable::replaceWrapChar(
const QVariant &variant )
const 724 if ( mWrapString.isEmpty() || !variant.toString().contains( mWrapString ) )
727 QString replaced = variant.toString();
728 replaced.replace( mWrapString, QLatin1String(
"\n" ) );
737 return mLayout->reportContext().layer();
740 if ( mDataDefinedVectorLayer )
741 return mDataDefinedVectorLayer;
743 return mVectorLayer.
get();
747 QgsRelation relation =
mLayout->project()->relationManager()->relation( mRelationId );
754 void QgsLayoutItemAttributeTable::removeLayer(
const QString &layerId )
758 if ( layerId == mVectorLayer->
id() )
768 static bool columnsBySortRank( QPair<int, QgsLayoutTableColumn * > a, QPair<int, QgsLayoutTableColumn * > b )
770 return a.second->sortByRank() < b.second->sortByRank();
776 QVector< QPair<int, QgsLayoutTableColumn * > > sortedColumns;
780 if ( column->sortByRank() > 0 )
782 sortedColumns.append( qMakePair( idx, column ) );
788 std::sort( sortedColumns.begin(), sortedColumns.end(), columnsBySortRank );
791 QVector<QPair<int, bool> > attributesBySortRank;
792 attributesBySortRank.reserve( sortedColumns.size() );
793 for (
auto &column : qgis::as_const( sortedColumns ) )
795 attributesBySortRank.append( qMakePair( column.first,
796 column.second->sortOrder() == Qt::AscendingOrder ) );
798 return attributesBySortRank;
803 if ( wrapString == mWrapString )
818 tableElem.setAttribute( QStringLiteral(
"source" ), QString::number( static_cast< int >( mSource ) ) );
819 tableElem.setAttribute( QStringLiteral(
"relationId" ), mRelationId );
820 tableElem.setAttribute( QStringLiteral(
"showUniqueRowsOnly" ), mShowUniqueRowsOnly );
821 tableElem.setAttribute( QStringLiteral(
"showOnlyVisibleFeatures" ), mShowOnlyVisibleFeatures );
822 tableElem.setAttribute( QStringLiteral(
"filterToAtlasIntersection" ), mFilterToAtlasIntersection );
823 tableElem.setAttribute( QStringLiteral(
"maxFeatures" ), mMaximumNumberOfFeatures );
824 tableElem.setAttribute( QStringLiteral(
"filterFeatures" ), mFilterFeatures ? QStringLiteral(
"true" ) : QStringLiteral(
"false" ) );
825 tableElem.setAttribute( QStringLiteral(
"featureFilter" ), mFeatureFilter );
826 tableElem.setAttribute( QStringLiteral(
"wrapString" ), mWrapString );
827 tableElem.setAttribute( QStringLiteral(
"useConditionalStyling" ), mUseConditionalStyling );
831 tableElem.setAttribute( QStringLiteral(
"mapUuid" ), mMap->
uuid() );
836 tableElem.setAttribute( QStringLiteral(
"vectorLayer" ), mVectorLayer.
layerId );
837 tableElem.setAttribute( QStringLiteral(
"vectorLayerName" ), mVectorLayer.
name );
838 tableElem.setAttribute( QStringLiteral(
"vectorLayerSource" ), mVectorLayer.
source );
839 tableElem.setAttribute( QStringLiteral(
"vectorLayerProvider" ), mVectorLayer.
provider );
856 mRelationId = itemElem.attribute( QStringLiteral(
"relationId" ), QString() );
860 mCurrentAtlasLayer =
mLayout->reportContext().layer();
863 mShowUniqueRowsOnly = itemElem.attribute( QStringLiteral(
"showUniqueRowsOnly" ), QStringLiteral(
"0" ) ).toInt();
864 mShowOnlyVisibleFeatures = itemElem.attribute( QStringLiteral(
"showOnlyVisibleFeatures" ), QStringLiteral(
"1" ) ).toInt();
865 mFilterToAtlasIntersection = itemElem.attribute( QStringLiteral(
"filterToAtlasIntersection" ), QStringLiteral(
"0" ) ).toInt();
866 mFilterFeatures = itemElem.attribute( QStringLiteral(
"filterFeatures" ), QStringLiteral(
"false" ) ) == QLatin1String(
"true" );
867 mFeatureFilter = itemElem.attribute( QStringLiteral(
"featureFilter" ), QString() );
868 mMaximumNumberOfFeatures = itemElem.attribute( QStringLiteral(
"maxFeatures" ), QStringLiteral(
"5" ) ).toInt();
869 mWrapString = itemElem.attribute( QStringLiteral(
"wrapString" ) );
870 mUseConditionalStyling = itemElem.attribute( QStringLiteral(
"useConditionalStyling" ), QStringLiteral(
"0" ) ).toInt();
873 mMapUuid = itemElem.attribute( QStringLiteral(
"mapUuid" ) );
883 QString layerId = itemElem.attribute( QStringLiteral(
"vectorLayer" ) );
884 QString layerName = itemElem.attribute( QStringLiteral(
"vectorLayerName" ) );
885 QString layerSource = itemElem.attribute( QStringLiteral(
"vectorLayerSource" ) );
886 QString layerProvider = itemElem.attribute( QStringLiteral(
"vectorLayerProvider" ) );
887 mVectorLayer =
QgsVectorLayerRef( layerId, layerName, layerSource, layerProvider );
902 if ( source == mSource )
911 if ( newLayer != prevLayer )
923 mCurrentAtlasLayer = newLayer;
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QString displayName() const override
Returns the multiframe display name.
The class is used as a container of context for various read/write operations on other objects...
Wrapper for iterator of features from vector data provider or vector layer.
Single variable definition for use within a QgsExpressionContextScope.
A rectangle specified with double values.
QString relationId() const
Returns the relation id which the table displays child features from.
void setMaximumNumberOfFeatures(int features)
Sets the maximum number of features shown by the table.
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.
Use exact geometry intersection (slower) instead of bounding boxes.
int type() const override
Returns unique multiframe type id.
A class to display a table in the print layout, and allow the table to span over multiple frames...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
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 extentChanged()
Emitted when the map's extent changes.
QgsVectorLayer referencingLayer
bool writePropertiesToElement(QDomElement &elem, QDomDocument &doc, const QgsReadWriteContext &context) const override
Stores multiframe state within an XML DOM element.
virtual void refreshAttributes()
Refreshes the contents shown in the table by querying for new data.
Container of fields for a vector layer.
A geometry is the spatial representation of a feature.
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
bool readPropertiesFromElement(const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context) override
Sets multiframe state from a DOM element.
Table shows attributes from related child features.
QString wrapString() const
Returns the string used to wrap the contents of the table cells by.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
bool qgsVariantGreaterThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is greater than the second.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
Table shows attributes from features in a vector layer.
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
Stores properties of a column for a QgsLayoutTable.
QgsConditionalLayerStyles * conditionalStyles() const
Returns the conditional styles that are set for this layer.
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
void setFilterToAtlasFeature(bool filterToAtlas)
Sets attribute table to only show features which intersect the current atlas feature.
void resetColumns()
Resets the attribute table's columns to match the vector layer's fields.
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
Attribute table source layer.
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.
QgsExpressionContextScope * lastScope()
Returns the last scope added to the context.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
Layout graphical items for displaying a map.
QString provider
Weak reference to layer provider.
QString layerId
Original layer ID.
QgsPropertyCollection mDataDefinedProperties
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
const QgsLayout * layout() const
Returns the layout the object is attached to.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
Conditional styling for a rule.
bool isEmpty() const
Returns true if the rectangle is empty.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
static QList< QgsConditionalStyle > matchingConditionalStyles(const QList< QgsConditionalStyle > &styles, const QVariant &value, QgsExpressionContext &context)
Find and return the matching styles for the value and feature.
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
QString name
Weak reference to layer name.
void setFeatureFilter(const QString &expression)
Sets the expression used for filtering features in the table.
QPointer< QgsLayout > mLayout
QgsVectorLayer * sourceLayer() const
Returns the source layer for the table, considering the table source mode.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
void setFilterFeatures(bool filter)
Sets whether the feature filter is active for the attribute table.
void setDisplayOnlyVisibleFeatures(bool visibleOnly)
Sets the attribute table to only show features which are visible in a map item.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts, annotations, canvases, etc.
A layout table subclass that displays attributes from a vector layer.
static QgsConditionalStyle compressStyles(const QList< QgsConditionalStyle > &styles)
Compress a list of styles into a single style.
Table shows attributes from the current atlas feature.
void layerChanged(QgsVectorLayer *layer)
Emitted when the context's layer is changed.
Encapsulate a field in an attribute table or data source.
QgsFeatureRequest getRelatedFeaturesRequest(const QgsFeature &feature) const
Creates a request to return all the features on the referencing (child) layer which have a foreign ke...
virtual void finalizeRestoreFromXml()
Called after all pending items have been restored from XML.
void setLayer(TYPE *l)
Sets the reference to point to a specified layer.
QString source
Weak reference to layer public source.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProject *project)
Resolves a string into a map layer from a given project.
static QgsLayoutItemAttributeTable * create(QgsLayout *layout)
Returns a new QgsLayoutItemAttributeTable for the specified parent layout.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
QVector< QPair< int, bool > > sortAttributes() const
Returns the attributes used to sort the table's features.
void setVectorLayer(QgsVectorLayer *layer)
Sets the vector layer from which to display feature attributes.
QPolygonF visibleExtentPolygon() const
Returns a polygon representing the current visible map extent, considering map extents and rotation...
void mapRotationChanged(double newRotation)
Emitted when the map's rotation changes.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
void setSource(ContentSource source)
Sets the source for attributes to show in table body.
QList< QgsConditionalStyle > fieldStyles(const QString &fieldName) const
Returns the conditional styles set for the field with matching fieldName.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
void setDisplayedFields(const QStringList &fields, bool refresh=true)
Sets the attributes to display in the table.
void layerWillBeRemoved(const QString &layerId)
Emitted when a layer is about to be removed from the registry.
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...
QgsLayoutTableColumns mColumns
Columns to show in table.
void setUniqueRowsOnly(bool uniqueOnly)
Sets attribute table to only show unique rows.
void finalizeRestoreFromXml() override
Called after all pending items have been restored from XML.
QgsLayoutTableContents & contents()
Returns the current contents of the table.
bool writePropertiesToElement(QDomElement &elem, QDomDocument &doc, const QgsReadWriteContext &context) const override
Stores multiframe state within an XML DOM element.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
QgsLayoutItemAttributeTable(QgsLayout *layout)
Constructor for QgsLayoutItemAttributeTable, attached to the specified layout.
void setWrapString(const QString &wrapString)
Sets a string to wrap the contents of the table cells by.
The QgsConditionalLayerStyles class holds conditional style information for a layer.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
virtual QString uuid() const
Returns the item identification string.
_LayerRef< QgsVectorLayer > QgsVectorLayerRef
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
void setRelationId(const QString &id)
Sets the relation id from which to display child features.
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...
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsConditionalStyle conditionalCellStyle(int row, int column) const override
Returns the conditional style to use for the cell at row, column.
bool useConditionalStyling() const
Returns true if the attribute table will be rendered using the conditional styling properties of the ...
void setMap(QgsLayoutItemMap *map)
Sets a layout map to use to limit the extent of features shown in the attribute table.
Custom exception class for Coordinate Reference System related exceptions.
ContentSource
Specifies the content source for the attribute table.
ContentSource source() const
Returns the source for attributes shown in the table body.
QgsLayoutItemMap * map() const
Returns the layout map whose extents are controlling the features shown in the table.
void setUseConditionalStyling(bool enabled)
Sets whether the attribute table will be rendered using the conditional styling properties of the lin...
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
bool nextFeature(QgsFeature &f)
void changed()
Emitted when the object's properties change.
Represents a vector layer which manages a vector based data sets.
TYPE * get() const
Returns a pointer to the layer, or nullptr if the reference has not yet been matched to a layer...
DataDefinedProperty
Data defined properties for different item types.
bool getTableContents(QgsLayoutTableContents &contents) override
Queries the attribute table's vector layer for attributes to show in the table.
QIcon icon() const override
Returns the item's icon.
void layerModified()
Emitted when modifications has been done on layer.
QString attributeDisplayName(int index) const
Convenience function that returns the attribute alias if defined or the field name else...
bool contentsContainsRow(const QgsLayoutTableContents &contents, const QgsLayoutTableRow &row) const
Checks whether a table contents contains a given row.
QVector< QgsLayoutTableRow > QgsLayoutTableContents
List of QgsLayoutTableRows, representing rows and column cell contents for a QgsLayoutTable.
QgsCoordinateReferenceSystem crs
QgsConditionalStyles rowStyles() const
Returns a list of row styles associated with the layer.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
bool readPropertiesFromElement(const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context) override
Sets multiframe state from a DOM element.
QVector< QVariant > QgsLayoutTableRow
List of QVariants, representing a the contents of a single row in a QgsLayoutTable.
void recalculateTableSize()
Recalculates and updates the size of the table and all table frames.
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...