16 #include <QItemSelectionModel>
37 : QSortFilterProxyModel( parent )
41 setDynamicSortFilter(
true );
45 mReloadVisibleTimer.setSingleShot(
true );
46 connect( &mReloadVisibleTimer, &QTimer::timeout,
this, &QgsAttributeTableFilterModel::reloadVisible );
47 mFilterFeaturesTimer.setSingleShot(
true );
58 if ( leftSelected && !rightSelected )
60 return sortOrder() == Qt::AscendingOrder;
62 else if ( rightSelected && !leftSelected )
64 return sortOrder() == Qt::DescendingOrder;
80 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
81 order = Qt::AscendingOrder;
82 if ( column < 0 || column >= mColumnMapping.size() )
88 int myColumn = mColumnMapping.at( column );
90 QSortFilterProxyModel::sort( myColumn, order );
97 if ( mapColumnToSource( index.column() ) == -1 )
103 QModelIndex fieldIndex = QSortFilterProxyModel::mapToSource( QSortFilterProxyModel::index( index.row(), 0, index.parent() ) );
110 return QSortFilterProxyModel::data( index, role );
115 if ( orientation == Qt::Horizontal )
117 if ( mColumnMapping.at( section ) == -1 && role == Qt::DisplayRole )
118 return tr(
"Actions" );
120 return QSortFilterProxyModel::headerData( section, orientation, role );
124 if ( role == Qt::DisplayRole )
128 int sourceSection =
mapToSource( index( section, ( !mColumnMapping.isEmpty() && mColumnMapping.at( 0 ) == -1 ) ? 1 : 0 ) ).row();
129 return sourceModel()->headerData( sourceSection, orientation, role );
136 return mColumnMapping.indexOf( -1 );
142 return mColumnMapping.count();
156 QVector<int> newColumnMapping;
157 const auto constColumns = mConfig.
columns();
161 if ( columnConfig.hidden )
166 newColumnMapping << newValue;
169 if ( newColumnMapping != mColumnMapping )
171 bool requiresReset =
false;
172 int firstRemovedColumn = -1;
173 int removedColumnCount = 0;
176 for (
int i = 0; i < std::min( newColumnMapping.size(), mColumnMapping.size() - removedColumnCount ); ++i )
178 if ( newColumnMapping.at( i ) == mColumnMapping.at( i + removedColumnCount ) )
181 if ( firstRemovedColumn == -1 )
183 firstRemovedColumn = i;
185 while ( i < mColumnMapping.size() - removedColumnCount && mColumnMapping.at( i + removedColumnCount ) != newColumnMapping.at( i ) )
187 ++removedColumnCount;
192 requiresReset =
true;
198 if ( firstRemovedColumn == -1 )
200 if ( newColumnMapping.size() > mColumnMapping.size() )
203 beginInsertColumns( QModelIndex(), mColumnMapping.size(), newColumnMapping.size() - 1 );
204 mColumnMapping = newColumnMapping;
210 beginRemoveColumns( QModelIndex(), newColumnMapping.size(), mColumnMapping.size() - 1 );
211 mColumnMapping = newColumnMapping;
217 if ( newColumnMapping.size() == mColumnMapping.size() - removedColumnCount )
220 beginRemoveColumns( QModelIndex(), firstRemovedColumn, firstRemovedColumn + removedColumnCount - 1 );
221 mColumnMapping = newColumnMapping;
226 requiresReset =
true;
233 mColumnMapping = newColumnMapping;
244 mFilterExpression = expression;
245 mFilterExpressionContext = context;
250 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
251 order = Qt::AscendingOrder;
253 QSortFilterProxyModel::sort( -1 );
255 QSortFilterProxyModel::sort( 0, order );
268 int column = sortColumn();
269 Qt::SortOrder order = sortOrder();
275 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
276 order = Qt::AscendingOrder;
278 sort( 0, Qt::AscendingOrder );
285 mTableModel = sourceModel;
289 mColumnMapping.append( i );
292 QSortFilterProxyModel::setSourceModel( sourceModel );
295 disconnect( mTableModel, SIGNAL( columnsAboutToBeInserted( QModelIndex,
int,
int ) ),
this, SLOT( _q_sourceColumnsAboutToBeInserted( QModelIndex,
int,
int ) ) );
296 disconnect( mTableModel, SIGNAL( columnsInserted( QModelIndex,
int,
int ) ),
this, SLOT( _q_sourceColumnsInserted( QModelIndex,
int,
int ) ) );
297 disconnect( mTableModel, SIGNAL( columnsAboutToBeRemoved( QModelIndex,
int,
int ) ),
this, SLOT( _q_sourceColumnsAboutToBeRemoved( QModelIndex,
int,
int ) ) );
298 disconnect( mTableModel, SIGNAL( columnsRemoved( QModelIndex,
int,
int ) ),
this, SLOT( _q_sourceColumnsRemoved( QModelIndex,
int,
int ) ) );
300 connect( mTableModel, &QAbstractItemModel::columnsAboutToBeInserted,
this, &QgsAttributeTableFilterModel::onColumnsChanged );
301 connect( mTableModel, &QAbstractItemModel::columnsAboutToBeRemoved,
this, &QgsAttributeTableFilterModel::onColumnsChanged );
307 return mSelectedOnTop;
312 mFilteredFeatures = ids;
320 ids.reserve( rowCount() );
321 for (
int i = 0; i < rowCount(); ++i )
323 QModelIndex row = index( i, 0 );
343 switch ( mFilterMode )
389 Q_UNUSED( sourceParent )
390 switch ( mFilterMode )
437 void QgsAttributeTableFilterModel::reloadVisible()
444 void QgsAttributeTableFilterModel::onAttributeValueChanged(
QgsFeatureId fid,
int idx,
const QVariant &value )
451 startTimedFilterFeatures();
455 void QgsAttributeTableFilterModel::onGeometryChanged()
459 startTimedFilterFeatures();
463 void QgsAttributeTableFilterModel::startTimedReloadVisible()
465 mReloadVisibleTimer.start( 10 );
468 void QgsAttributeTableFilterModel::startTimedFilterFeatures()
470 mFilterFeaturesTimer.start( 10 );
475 if ( !mFilterExpression.
isValid() )
486 QApplication::setOverrideCursor( Qt::WaitCursor );
512 if ( mFilterExpression.
evaluate( &mFilterExpressionContext ).toInt() != 0 )
516 if ( mFilterExpression.
hasEvalError() && error.isEmpty() )
526 QApplication::restoreOverrideCursor();
530 if ( ! error.isEmpty() )
538 void QgsAttributeTableFilterModel::selectionChanged()
544 else if ( mSelectedOnTop )
550 void QgsAttributeTableFilterModel::onColumnsChanged()
555 int QgsAttributeTableFilterModel::mapColumnToSource(
int column )
const
557 if ( mColumnMapping.isEmpty() )
559 if ( column < 0 || column >= mColumnMapping.size() )
562 return mColumnMapping.at( column );
565 int QgsAttributeTableFilterModel::mapColumnFromSource(
int column )
const
567 if ( mColumnMapping.isEmpty() )
570 return mColumnMapping.indexOf( column );
583 mFilteredFeatures.clear();
584 if ( !
layer()->renderer() )
586 QgsDebugMsg( QStringLiteral(
"Cannot get renderer" ) );
590 std::unique_ptr< QgsFeatureRenderer > renderer(
layer()->renderer()->clone() );
595 QgsDebugMsg( QStringLiteral(
"Out of scale limits" ) );
613 renderer->startRender( renderContext,
layer()->fields() );
632 const QString temporalFilter = qobject_cast< const QgsVectorLayerTemporalProperties * >(
layer()->temporalProperties() )->createFilterString( temporalContext, mCanvas->
mapSettings().
temporalRange() );
633 if ( !temporalFilter.isEmpty() )
644 if ( !filter || renderer->willRenderFeature( f, renderContext ) )
646 mFilteredFeatures << f.
id();
649 if ( t.elapsed() > 5000 )
652 emit progress( i, cancel );
665 renderer->stopRender( renderContext );
681 QModelIndexList indexes;
683 for (
const QModelIndex &idx : constIdToIndexList )
693 if ( !proxyIndex.isValid() )
694 return QModelIndex();
696 int sourceColumn = mapColumnToSource( proxyIndex.column() );
700 if ( sourceColumn == -1 )
703 return QSortFilterProxyModel::mapToSource( index( proxyIndex.row(), sourceColumn, proxyIndex.parent() ) );
708 QModelIndex proxyIndex = QSortFilterProxyModel::mapFromSource( sourceIndex );
710 if ( proxyIndex.column() < 0 )
711 return QModelIndex();
713 int col = mapColumnFromSource( proxyIndex.column() );
718 return index( proxyIndex.row(), col, proxyIndex.parent() );
724 if ( mapColumnToSource( index.column() ) == -1 )
725 return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
This is a container for configuration of the attribute table.
@ Action
This column represents an action widget.
Qt::SortOrder sortOrder() const
Gets the sort order.
QVector< QgsAttributeTableConfig::ColumnConfig > columns() const
Gets the list with all columns and their configuration.
void update(const QgsFields &fields)
Update the configuration with the given fields.
QString sortExpression() const
Gets the expression used for sorting.
bool hasSameColumns(const QgsAttributeTableConfig &other) const
Compare this configuration's columns name, type, and order to other.
QModelIndex mapToSource(const QModelIndex &proxyIndex) const override
QString sortExpression() const
The expression which is used to sort the attribute table.
FilterMode filterMode()
The current filterModel.
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override
@ TypeRole
The type of a given column.
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.
QgsVectorLayer * layer() const
Returns the layer this filter acts on.
void setFilterMode(FilterMode filterMode)
Set the filter mode the filter will use.
int columnCount(const QModelIndex &parent) const override
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.
QModelIndex fidToIndex(QgsFeatureId fid) override
void setAttributeTableConfig(const QgsAttributeTableConfig &config)
Set the attribute table configuration to control which fields are shown, in which order they are show...
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override
Used by the sorting algorithm.
FilterMode
The filter mode defines how the rows should be filtered.
@ ShowFilteredList
Show only features whose ids are on the filter list. {.
@ ShowVisible
Show only visible features (depends on the map canvas)
@ ShowSelected
Show only selected features.
@ ShowEdited
Show only features which have unsaved changes.
@ ShowAll
Show all features.
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.
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.
QgsFeatureId rowToId(const QModelIndex &row)
Returns the feature id for a given model index.
QVariant headerData(int section, Qt::Orientation orientation, int role) const override
QVariant data(const QModelIndex &index, int role) const override
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.
QgsFeatureIds filteredFeatures()
Gets a list of currently filtered feature ids.
void setSourceModel(QgsAttributeTableModel *sourceModel)
Set the attribute table model that backs this model.
void setSelectedOnTop(bool selectedOnTop)
Changes the sort order of the features.
QgsAttributeTableModel * masterModel() const
Returns the table model this filter is using.
void sortColumnChanged(int column, Qt::SortOrder order)
Emitted whenever the sort column is changed.
void connectFilterModeConnections(FilterMode filterMode)
Disconnect the connections set for the new filterMode.
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...
const QgsFeatureRequest & request() const
Gets the the feature request.
Qt::ItemFlags flags(const QModelIndex &index) const override
Returns item flags for the index.
QgsVectorLayer * layer() const
Returns the layer this model uses as backend.
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.
int extraColumns() const
Empty extra columns to announce from this model.
int columnCount(const QModelIndex &parent=QModelIndex()) const override
Returns the number of columns.
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.
@ SortRole
Role used for sorting start here.
@ FeatureIdRole
Get the feature id of the feature in this row.
void prefetchColumnData(int column)
Caches the entire data for one column.
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.
Class for parsing and evaluation of expressions (formerly called "search strings").
QString evalErrorString() const
Returns evaluation error.
void setDistanceUnits(QgsUnitTypes::DistanceUnit unit)
Sets the desired distance units for calculations involving geomCalculator(), e.g.,...
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
void setAreaUnits(QgsUnitTypes::AreaUnit unit)
Sets the desired areal units for calculations involving geomCalculator(), e.g., "$area".
void setGeomCalculator(const QgsDistanceArea *calc)
Sets the geometry calculator used for distance and area calculations in expressions.
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
bool needsGeometry() const
Returns true if the expression uses feature geometry for some computation.
QVariant evaluate()
Evaluate the feature and return the result.
bool isValid() const
Checks if this expression is valid.
QSet< int > referencedAttributeIndexes(const QgsFields &fields) const
Returns a list of field name indexes obtained from the provided fields.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
@ 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 ....
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 & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
const QgsRectangle & filterRect() const
Returns the rectangle from which features will be taken.
const Flags & flags() const
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...
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
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.
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
QgsRectangle extent() const
Returns the current zoom extent of the map canvas.
QgsCoordinateReferenceSystem crs
The QgsMapSettings class contains configuration for rendering of the map.
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 takes output image size into accou...
QgsPointXY mapToLayerCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from output CRS to layer's CRS
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsCoordinateTransformContext transformContext
A rectangle specified with double values.
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
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.
const QgsDateTimeRange & temporalRange() const
Returns the datetime range for the object.
bool isTemporal() const
Returns true if the object's temporal range is enabled, and the object will be filtered when renderin...
QgsFeatureIterator getFeatures(const QgsFeatureRequest &featureRequest=QgsFeatureRequest())
Query this VectorLayerCache for features.
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.
Encapsulates the context in which a QgsVectorLayer's temporal capabilities will be applied.
void setLayer(QgsVectorLayer *layer)
Sets the associated layer.
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.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
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.
Q_INVOKABLE QgsVectorLayerEditBuffer * editBuffer()
Buffer with uncommitted editing operations. Only valid after editing has been turned on.
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
Defines the configuration of a column in the attribute table.