33#include <QApplication>
34#include <QItemSelectionModel>
37#include "moc_qgsattributetablefiltermodel.cpp"
39using namespace Qt::StringLiterals;
46 : QSortFilterProxyModel( parent )
50 setDynamicSortFilter(
true );
54 mReloadVisibleTimer.setSingleShot(
true );
55 connect( &mReloadVisibleTimer, &QTimer::timeout,
this, &QgsAttributeTableFilterModel::reloadVisible );
56 mFilterFeaturesTimer.setSingleShot(
true );
67 if ( leftSelected && !rightSelected )
69 return sortOrder() == Qt::AscendingOrder;
71 else if ( rightSelected && !leftSelected )
73 return sortOrder() == Qt::DescendingOrder;
77 if ( mTableModel->sortCacheExpression().isEmpty() )
88 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
89 order = Qt::AscendingOrder;
90 if ( column < 0 || column >= mColumnMapping.size() )
96 const int myColumn = mColumnMapping.at( column );
98 QSortFilterProxyModel::sort( myColumn, order );
105 if ( mapColumnToSource( index.column() ) == -1 )
111 const QModelIndex fieldIndex = QSortFilterProxyModel::mapToSource( QSortFilterProxyModel::index( index.row(), 0, index.parent() ) );
116 const QModelIndex fieldIndex = QSortFilterProxyModel::mapToSource( QSortFilterProxyModel::index( index.row(), 0, index.parent() ) );
123 return QSortFilterProxyModel::data( index, role );
128 if ( orientation == Qt::Horizontal )
130 if ( mColumnMapping.at( section ) == -1 && role == Qt::DisplayRole )
131 return tr(
"Actions" );
134 const int sourceSection = mapColumnToSource( section );
135 return sourceModel()->headerData( sourceSection, orientation, role );
140 if ( role == Qt::DisplayRole )
144 const int sourceSection =
mapToSource( index( section, ( !mColumnMapping.isEmpty() && mColumnMapping.at( 0 ) == -1 ) ? 1 : 0 ) ).row();
145 return sourceModel()->headerData( sourceSection, orientation, role );
152 return mColumnMapping.indexOf( -1 );
157 if ( parent.isValid() )
160 return mColumnMapping.count();
169 if ( !force && mConfig.hasSameColumns( oldConfig ) )
174 QVector<int> newColumnMapping;
175 const auto constColumns = mConfig.columns();
179 if ( columnConfig.hidden )
184 newColumnMapping << newValue;
187 if ( newColumnMapping != mColumnMapping )
189 bool requiresReset =
false;
190 int firstRemovedColumn = -1;
191 int removedColumnCount = 0;
194 for (
int i = 0; i < std::min( newColumnMapping.size(), mColumnMapping.size() - removedColumnCount ); ++i )
196 if ( newColumnMapping.at( i ) == mColumnMapping.at( i + removedColumnCount ) )
199 if ( firstRemovedColumn == -1 )
201 firstRemovedColumn = i;
203 while ( i < mColumnMapping.size() - removedColumnCount && mColumnMapping.at( i + removedColumnCount ) != newColumnMapping.at( i ) )
205 ++removedColumnCount;
210 requiresReset =
true;
216 if ( firstRemovedColumn == -1 )
218 if ( newColumnMapping.size() > mColumnMapping.size() )
221 beginInsertColumns( QModelIndex(), mColumnMapping.size(), newColumnMapping.size() - 1 );
222 mColumnMapping = newColumnMapping;
228 beginRemoveColumns( QModelIndex(), newColumnMapping.size(), mColumnMapping.size() - 1 );
229 mColumnMapping = newColumnMapping;
235 if ( newColumnMapping.size() == mColumnMapping.size() - removedColumnCount )
238 beginRemoveColumns( QModelIndex(), firstRemovedColumn, firstRemovedColumn + removedColumnCount - 1 );
239 mColumnMapping = newColumnMapping;
244 requiresReset =
true;
251 mColumnMapping = newColumnMapping;
264 mFilterExpression = expression;
265 mFilterExpressionContext = context;
270 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
271 order = Qt::AscendingOrder;
273 QSortFilterProxyModel::sort( -1 );
275 QSortFilterProxyModel::sort( 0, order );
288 int column = sortColumn();
289 Qt::SortOrder order = sortOrder();
295 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
296 order = Qt::AscendingOrder;
298 sort( column, order );
305 mTableModel = sourceModel;
307 for (
int i = 0; i < mTableModel->columnCount() - mTableModel->extraColumns(); ++i )
309 mColumnMapping.append( i );
312 QSortFilterProxyModel::setSourceModel( sourceModel );
315 connect( mTableModel, &QAbstractItemModel::columnsAboutToBeInserted,
this, &QgsAttributeTableFilterModel::onColumnsChanged );
316 connect( mTableModel, &QAbstractItemModel::columnsAboutToBeRemoved,
this, &QgsAttributeTableFilterModel::onColumnsChanged );
321 return mSelectedOnTop;
326 mFilteredFeatures = ids;
337 ids.reserve( rowCount() );
338 for (
int i = 0; i < rowCount(); ++i )
340 const QModelIndex row = index( i, 0 );
365 switch ( mFilterMode )
413 Q_UNUSED( sourceParent )
414 switch ( mFilterMode )
462void QgsAttributeTableFilterModel::reloadVisible()
469void QgsAttributeTableFilterModel::onAttributeValueChanged(
QgsFeatureId fid,
int idx,
const QVariant &value )
476 startTimedFilterFeatures();
480void QgsAttributeTableFilterModel::onGeometryChanged()
484 startTimedFilterFeatures();
488void QgsAttributeTableFilterModel::startTimedReloadVisible()
490 mReloadVisibleTimer.start( 10 );
493void QgsAttributeTableFilterModel::startTimedFilterFeatures()
495 mFilterFeaturesTimer.start( 10 );
500 if ( !mFilterExpression.isValid() )
509 const bool fetchGeom = mFilterExpression.needsGeometry();
511 QApplication::setOverrideCursor( Qt::WaitCursor );
513 mFilterExpression.setGeomCalculator( &distanceArea );
517 request.
setSubsetOfAttributes( mFilterExpression.referencedColumns(), mTableModel->layer()->fields() );
536 mFilterExpressionContext.setFeature( f );
537 if ( mFilterExpression.evaluate( &mFilterExpressionContext ).toInt() != 0 )
541 if ( mFilterExpression.hasEvalError() && error.isEmpty() )
543 error = mFilterExpression.evalErrorString();
551 QApplication::restoreOverrideCursor();
555 if ( !error.isEmpty() )
562void QgsAttributeTableFilterModel::selectionChanged()
568 else if ( mSelectedOnTop )
574void QgsAttributeTableFilterModel::onColumnsChanged()
579int QgsAttributeTableFilterModel::mapColumnToSource(
int column )
const
581 if ( mColumnMapping.isEmpty() )
583 if ( column < 0 || column >= mColumnMapping.size() )
586 return mColumnMapping.at( column );
589int QgsAttributeTableFilterModel::mapColumnFromSource(
int column )
const
591 if ( mColumnMapping.isEmpty() )
594 return mColumnMapping.indexOf( column );
607 mFilteredFeatures.clear();
608 if ( !
layer()->renderer() )
614 std::unique_ptr<QgsFeatureRenderer> renderer(
layer()->renderer()->clone() );
637 renderer->startRender( renderContext,
layer()->fields() );
650 if ( canvasFilter ==
"FALSE"_L1 )
652 if ( !canvasFilter.isEmpty() )
662 if ( !filter || renderer->willRenderFeature( f, renderContext ) )
664 mFilteredFeatures << f.
id();
667 if ( t.elapsed() > 5000 )
670 emit progress( i, cancel );
683 renderer->stopRender( renderContext );
699 QModelIndexList indexes;
701 for (
const QModelIndex &idx : constIdToIndexList )
711 if ( !proxyIndex.isValid() )
712 return QModelIndex();
714 int sourceColumn = mapColumnToSource( proxyIndex.column() );
717 if ( sourceColumn == -1 )
718 return QModelIndex();
720 return QSortFilterProxyModel::mapToSource( index( proxyIndex.row(), sourceColumn, proxyIndex.parent() ) );
725 const QModelIndex proxyIndex = QSortFilterProxyModel::mapFromSource( sourceIndex );
727 if ( proxyIndex.column() < 0 )
728 return QModelIndex();
730 int col = mapColumnFromSource( proxyIndex.column() );
735 return index( proxyIndex.row(), col, proxyIndex.parent() );
740 if ( !index.isValid() )
741 return Qt::ItemFlag::NoItemFlags;
744 if ( mapColumnToSource( index.column() ) == -1 )
745 return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
747 const QModelIndex source_index =
mapToSource( index );
753 if ( !proxyIndex.isValid() )
754 return QModelIndex();
756 int sourceColumn = mapColumnToSource( proxyIndex.column() );
760 if ( sourceColumn == -1 )
763 return QSortFilterProxyModel::mapToSource( index( proxyIndex.row(), sourceColumn, proxyIndex.parent() ) );
AttributeTableFilterMode
Defines how rows in attribute tables should be filtered.
@ ShowSelected
Show only selected features.
@ ShowAll
Show all features.
@ ShowInvalid
Show only features not respecting constraints.
@ ShowVisible
Show only visible features (depends on the map canvas).
@ ShowFilteredList
Show only features whose IDs are on the filter list.
@ ShowEdited
Show only features which have unsaved changes.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
@ BoundingBox
Filter using a bounding box.
A container for configuration of the attribute table.
@ Action
This column represents an action widget.
Qt::SortOrder sortOrder() const
Gets the sort order.
void update(const QgsFields &fields)
Update the configuration with the given fields.
QString sortExpression() const
Gets the expression used for sorting.
QgsFeatureIds filteredFeatures() const
Gets a list of currently filtered feature ids.
QModelIndex mapToSource(const QModelIndex &proxyIndex) const override
QString sortExpression() const
The expression which is used to sort the attribute table.
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override
Q_DECL_DEPRECATED void extentsChanged()
Is called upon every change of the visible extents on the map canvas.
void sort(int column, Qt::SortOrder order=Qt::AscendingOrder) override
Sort by the given column using the given order.
QgsAttributeTableFilterModel(QgsMapCanvas *canvas, QgsAttributeTableModel *sourceModel, QObject *parent=nullptr)
Make sure, the master model is already loaded, so the selection will get synchronized.
void setFilterMode(Qgis::AttributeTableFilterMode filterMode)
Set the filter mode the filter will use.
int columnCount(const QModelIndex &parent) const override
void setAttributeTableConfig(const QgsAttributeTableConfig &config, bool force=false)
Set the attribute table configuration to control which fields are shown, in which order they are show...
void generateListOfVisibleFeatures()
Updates the list of currently visible features on the map canvas.
QModelIndexList fidToIndexList(QgsFeatureId fid)
void disconnectFilterModeConnections()
Disconnect the connections set for the current filterMode.
QgsFeatureId rowToId(const QModelIndex &row) const
Returns the feature id for a given model index.
@ Type
The type of a given column.
QModelIndex fidToIndex(QgsFeatureId fid) override
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override
Used by the sorting algorithm.
bool selectedOnTop()
Returns if selected features are currently shown on top.
void filterError(const QString &errorMessage)
Emitted when an error occurred while filtering features.
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override
Returns true if the source row will be accepted.
void connectFilterModeConnections(Qgis::AttributeTableFilterMode filterMode)
Disconnect the connections set for the new filterMode.
QModelIndex mapFromMaster(const QModelIndex &sourceIndex) const
void filterFeatures()
Updates the filtered features in the filter model.
int actionColumnIndex() const
Gets the index of the first column that contains an action widget.
void setFilterExpression(const QgsExpression &expression, const QgsExpressionContext &context)
Set the expression and the context to be stored in case of the features need to be filtered again (li...
virtual void setFilteredFeatures(const QgsFeatureIds &ids)
Specify a list of features, which the filter will accept.
QgsAttributeTableModel * masterModel() const
Returns the table model this filter is using.
QVariant headerData(int section, Qt::Orientation orientation, int role) const override
QVariant data(const QModelIndex &index, int role) const override
Qgis::AttributeTableFilterMode filterMode()
The current filterModel.
QModelIndex mapToMaster(const QModelIndex &proxyIndex) const
void featuresFiltered()
Emitted when the filtering of the features has been done.
void visibleReloaded()
Emitted when the the visible features on extend are reloaded (the list is created).
@ ColumnTypeActionButton
This column shows action buttons.
@ ColumnTypeField
This column shows a field.
void setSourceModel(QgsAttributeTableModel *sourceModel)
Set the attribute table model that backs this model.
QgsVectorLayer * layer() const
Returns the layer this filter acts on.
void setSelectedOnTop(bool selectedOnTop)
Changes the sort order of the features.
void sortColumnChanged(int column, Qt::SortOrder order)
Emitted whenever the sort column is changed.
Qt::ItemFlags flags(const QModelIndex &index) const override
A model backed by a QgsVectorLayerCache which is able to provide feature/attribute information to a Q...
Qt::ItemFlags flags(const QModelIndex &index) const override
Returns item flags for the index.
QString sortCacheExpression(unsigned long cacheIndex=0) const
The expression which was used to fill the sorting cache at index cacheIndex.
QgsVectorLayerCache * layerCache() const
Returns the layer cache this model uses as backend.
QModelIndexList idToIndexList(QgsFeatureId id) const
void prefetchSortData(const QString &expression, unsigned long cacheIndex=0)
Prefetches the entire data for an expression.
QgsFeatureId rowToId(int row) const
Maps row to feature id.
void prefetchColumnData(int column)
Caches the entire data for one column.
@ FeatureId
Get the feature id of the feature in this row.
@ Sort
Role used for sorting start here.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
bool close()
Call to end the iteration.
@ ScaleDependent
Depends on scale if feature will be rendered (rule based ).
@ Filter
Features may be filtered, i.e. some features may not be rendered (categorized, rule based ....
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsRectangle filterRect() const
Returns the rectangle from which features will be taken.
Qgis::FeatureRequestFlags flags() const
Returns the flags which affect how features are fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
Qgis::SpatialFilterType spatialFilterType() const
Returns the spatial filter type which is currently set on this request.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
static QString filterForLayer(QgsMapCanvas *canvas, QgsVectorLayer *layer)
Constructs a filter to use for selecting features from the given layer, in order to apply filters whi...
Map canvas is a class for displaying all GIS data types on a canvas.
void extentsChanged()
Emitted when the extents of the map change.
void temporalRangeChanged()
Emitted when the map canvas temporal range changes.
Contains configuration for rendering maps.
double scale() const
Returns the calculated map scale.
const QgsMapToPixel & mapToPixel() const
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes output image size into account.
static QgsProject * instance()
Returns the QgsProject singleton instance.
A rectangle specified with double values.
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
Contains information about the context of a rendering operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setExtent(const QgsRectangle &extent)
When rendering a map layer, calling this method sets the "clipping" extent for the layer (in the laye...
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
void setRendererScale(double scale)
Sets the renderer map scale.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &featureRequest=QgsFeatureRequest())
Query this VectorLayerCache for features.
Stores queued vector layer edit operations prior to committing changes to the layer's data provider.
bool isFeatureAdded(QgsFeatureId id) const
Returns true if the specified feature ID has been added but not committed.
bool isFeatureAttributesChanged(QgsFeatureId id) const
Returns true if the specified feature ID has had an attribute changed but not committed.
bool isFeatureGeometryChanged(QgsFeatureId id) const
Returns true if the specified feature ID has had its geometry changed but not committed.
QgsRectangle extent() const final
Returns the extent of the layer.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
Q_INVOKABLE QgsVectorLayerEditBuffer * editBuffer()
Buffer with uncommitted editing operations. Only valid after editing has been turned on.
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant &value)
Emitted whenever an attribute value change is done in the edit buffer.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer.
void geometryChanged(QgsFeatureId fid, const QgsGeometry &geometry)
Emitted whenever a geometry change is done in the edit buffer.
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
Defines the configuration of a column in the attribute table.