QGIS API Documentation
3.26.3-Buenos Aires (65e4edfdad)
|
Go to the documentation of this file.
16 #include <QItemSelectionModel>
40 : QSortFilterProxyModel( parent )
44 setDynamicSortFilter(
true );
48 mReloadVisibleTimer.setSingleShot(
true );
49 connect( &mReloadVisibleTimer, &QTimer::timeout,
this, &QgsAttributeTableFilterModel::reloadVisible );
50 mFilterFeaturesTimer.setSingleShot(
true );
61 if ( leftSelected && !rightSelected )
63 return sortOrder() == Qt::AscendingOrder;
65 else if ( rightSelected && !leftSelected )
67 return sortOrder() == Qt::DescendingOrder;
83 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
84 order = Qt::AscendingOrder;
85 if ( column < 0 || column >= mColumnMapping.size() )
91 const int myColumn = mColumnMapping.at( column );
93 QSortFilterProxyModel::sort( myColumn, order );
100 if ( mapColumnToSource( index.column() ) == -1 )
106 const QModelIndex fieldIndex = QSortFilterProxyModel::mapToSource( QSortFilterProxyModel::index( index.row(), 0, index.parent() ) );
113 return QSortFilterProxyModel::data( index, role );
118 if ( orientation == Qt::Horizontal )
120 if ( mColumnMapping.at( section ) == -1 && role == Qt::DisplayRole )
121 return tr(
"Actions" );
123 return QSortFilterProxyModel::headerData( section, orientation, role );
127 if ( role == Qt::DisplayRole )
131 const int sourceSection =
mapToSource( index( section, ( !mColumnMapping.isEmpty() && mColumnMapping.at( 0 ) == -1 ) ? 1 : 0 ) ).row();
132 return sourceModel()->headerData( sourceSection, orientation, role );
139 return mColumnMapping.indexOf( -1 );
145 return mColumnMapping.count();
159 QVector<int> newColumnMapping;
160 const auto constColumns = mConfig.
columns();
164 if ( columnConfig.hidden )
169 newColumnMapping << newValue;
172 if ( newColumnMapping != mColumnMapping )
174 bool requiresReset =
false;
175 int firstRemovedColumn = -1;
176 int removedColumnCount = 0;
179 for (
int i = 0; i < std::min( newColumnMapping.size(), mColumnMapping.size() - removedColumnCount ); ++i )
181 if ( newColumnMapping.at( i ) == mColumnMapping.at( i + removedColumnCount ) )
184 if ( firstRemovedColumn == -1 )
186 firstRemovedColumn = i;
188 while ( i < mColumnMapping.size() - removedColumnCount && mColumnMapping.at( i + removedColumnCount ) != newColumnMapping.at( i ) )
190 ++removedColumnCount;
195 requiresReset =
true;
201 if ( firstRemovedColumn == -1 )
203 if ( newColumnMapping.size() > mColumnMapping.size() )
206 beginInsertColumns( QModelIndex(), mColumnMapping.size(), newColumnMapping.size() - 1 );
207 mColumnMapping = newColumnMapping;
213 beginRemoveColumns( QModelIndex(), newColumnMapping.size(), mColumnMapping.size() - 1 );
214 mColumnMapping = newColumnMapping;
220 if ( newColumnMapping.size() == mColumnMapping.size() - removedColumnCount )
223 beginRemoveColumns( QModelIndex(), firstRemovedColumn, firstRemovedColumn + removedColumnCount - 1 );
224 mColumnMapping = newColumnMapping;
229 requiresReset =
true;
236 mColumnMapping = newColumnMapping;
247 mFilterExpression = expression;
248 mFilterExpressionContext = context;
253 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
254 order = Qt::AscendingOrder;
256 QSortFilterProxyModel::sort( -1 );
258 QSortFilterProxyModel::sort( 0, order );
271 int column = sortColumn();
272 Qt::SortOrder order = sortOrder();
278 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
279 order = Qt::AscendingOrder;
281 sort( 0, Qt::AscendingOrder );
288 mTableModel = sourceModel;
292 mColumnMapping.append( i );
295 QSortFilterProxyModel::setSourceModel( sourceModel );
298 disconnect( mTableModel, SIGNAL( columnsAboutToBeInserted( QModelIndex,
int,
int ) ),
this, SLOT( _q_sourceColumnsAboutToBeInserted( QModelIndex,
int,
int ) ) );
299 disconnect( mTableModel, SIGNAL( columnsInserted( QModelIndex,
int,
int ) ),
this, SLOT( _q_sourceColumnsInserted( QModelIndex,
int,
int ) ) );
300 disconnect( mTableModel, SIGNAL( columnsAboutToBeRemoved( QModelIndex,
int,
int ) ),
this, SLOT( _q_sourceColumnsAboutToBeRemoved( QModelIndex,
int,
int ) ) );
301 disconnect( mTableModel, SIGNAL( columnsRemoved( QModelIndex,
int,
int ) ),
this, SLOT( _q_sourceColumnsRemoved( QModelIndex,
int,
int ) ) );
303 connect( mTableModel, &QAbstractItemModel::columnsAboutToBeInserted,
this, &QgsAttributeTableFilterModel::onColumnsChanged );
304 connect( mTableModel, &QAbstractItemModel::columnsAboutToBeRemoved,
this, &QgsAttributeTableFilterModel::onColumnsChanged );
310 return mSelectedOnTop;
315 mFilteredFeatures = ids;
323 ids.reserve( rowCount() );
324 for (
int i = 0; i < rowCount(); ++i )
326 const QModelIndex row = index( i, 0 );
346 switch ( mFilterMode )
392 Q_UNUSED( sourceParent )
393 switch ( mFilterMode )
440 void QgsAttributeTableFilterModel::reloadVisible()
447 void QgsAttributeTableFilterModel::onAttributeValueChanged(
QgsFeatureId fid,
int idx,
const QVariant &value )
454 startTimedFilterFeatures();
458 void QgsAttributeTableFilterModel::onGeometryChanged()
462 startTimedFilterFeatures();
466 void QgsAttributeTableFilterModel::startTimedReloadVisible()
468 mReloadVisibleTimer.start( 10 );
471 void QgsAttributeTableFilterModel::startTimedFilterFeatures()
473 mFilterFeaturesTimer.start( 10 );
478 if ( !mFilterExpression.
isValid() )
489 QApplication::setOverrideCursor( Qt::WaitCursor );
515 if ( mFilterExpression.
evaluate( &mFilterExpressionContext ).toInt() != 0 )
519 if ( mFilterExpression.
hasEvalError() && error.isEmpty() )
529 QApplication::restoreOverrideCursor();
533 if ( ! error.isEmpty() )
541 void QgsAttributeTableFilterModel::selectionChanged()
547 else if ( mSelectedOnTop )
553 void QgsAttributeTableFilterModel::onColumnsChanged()
558 int QgsAttributeTableFilterModel::mapColumnToSource(
int column )
const
560 if ( mColumnMapping.isEmpty() )
562 if ( column < 0 || column >= mColumnMapping.size() )
565 return mColumnMapping.at( column );
568 int QgsAttributeTableFilterModel::mapColumnFromSource(
int column )
const
570 if ( mColumnMapping.isEmpty() )
573 return mColumnMapping.indexOf( column );
586 mFilteredFeatures.clear();
587 if ( !
layer()->renderer() )
589 QgsDebugMsg( QStringLiteral(
"Cannot get renderer" ) );
593 std::unique_ptr< QgsFeatureRenderer > renderer(
layer()->renderer()->clone() );
598 QgsDebugMsg( QStringLiteral(
"Out of scale limits" ) );
616 renderer->startRender( renderContext,
layer()->fields() );
629 if ( canvasFilter == QLatin1String(
"FALSE" ) )
631 if ( !canvasFilter.isEmpty() )
641 if ( !filter || renderer->willRenderFeature( f, renderContext ) )
643 mFilteredFeatures << f.
id();
646 if ( t.elapsed() > 5000 )
649 emit progress( i, cancel );
662 renderer->stopRender( renderContext );
678 QModelIndexList indexes;
680 for (
const QModelIndex &idx : constIdToIndexList )
690 if ( !proxyIndex.isValid() )
691 return QModelIndex();
693 int sourceColumn = mapColumnToSource( proxyIndex.column() );
697 if ( sourceColumn == -1 )
700 return QSortFilterProxyModel::mapToSource( index( proxyIndex.row(), sourceColumn, proxyIndex.parent() ) );
705 const QModelIndex proxyIndex = QSortFilterProxyModel::mapFromSource( sourceIndex );
707 if ( proxyIndex.column() < 0 )
708 return QModelIndex();
710 int col = mapColumnFromSource( proxyIndex.column() );
715 return index( proxyIndex.row(), col, proxyIndex.parent() );
721 if ( mapColumnToSource( index.column() ) == -1 )
722 return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
724 const QModelIndex source_index =
mapToSource( index );
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
Qt::SortOrder sortOrder() const
Gets the sort order.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QgsCoordinateReferenceSystem crs
Q_INVOKABLE QgsVectorLayerEditBuffer * editBuffer()
Buffer with uncommitted editing operations. Only valid after editing has been turned on.
@ ShowAll
Show all features.
@ Filter
Features may be filtered, i.e. some features may not be rendered (categorized, rule based ....
bool isFeatureAttributesChanged(QgsFeatureId id) const
Returns true if the specified feature ID has had an attribute changed but not committed.
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
QgsRectangle extent() const
Returns the current zoom extent of the map canvas.
QString sortExpression() const
Gets the expression used for sorting.
QgsPointXY mapToLayerCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from output CRS to layer's CRS
QModelIndexList idToIndexList(QgsFeatureId id) const
void setDistanceUnits(QgsUnitTypes::DistanceUnit unit)
Sets the desired distance units for calculations involving geomCalculator(), e.g.,...
QString sortExpression() const
The expression which is used to sort the attribute table.
QgsExpressionContext & expressionContext()
Gets the expression context.
void visibleReloaded()
Emitted when the the visible features on extend are reloaded (the list is created)
QString evalErrorString() const
Returns evaluation error.
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
void connectFilterModeConnections(FilterMode filterMode)
Disconnect the connections set for the new filterMode.
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
void setSourceModel(QgsAttributeTableModel *sourceModel)
Set the attribute table model that backs this model.
@ ShowFilteredList
Show only features whose ids are on the filter list. {.
Q_DECL_DEPRECATED void extentsChanged()
Is called upon every change of the visible extents on the map canvas.
void temporalRangeChanged()
Emitted when the map canvas temporal range changes.
QSet< int > referencedAttributeIndexes(const QgsFields &fields) const
Returns a list of field name indexes obtained from the provided fields.
Map canvas is a class for displaying all GIS data types on a canvas.
bool isValid() const
Checks if this expression is valid.
Defines the configuration of a column in the attribute table.
void sort(int column, Qt::SortOrder order=Qt::AscendingOrder) override
Sort by the given column using the given order.
QgsCoordinateTransformContext transformContext
Contains information about the context of a rendering operation.
QgsRectangle filterRect() const
Returns the rectangle from which features will be taken.
static QgsProject * instance()
Returns the QgsProject singleton instance.
@ ShowEdited
Show only features which have unsaved changes.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &featureRequest=QgsFeatureRequest())
Query this VectorLayerCache for features.
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
QgsFeatureIds filteredFeatures()
Gets a list of currently filtered feature ids.
A rectangle specified with double values.
int columnCount(const QModelIndex &parent) const override
Flags flags() const
Returns the flags which affect how features are fetched.
@ ColumnTypeField
This column shows a field.
bool isFeatureGeometryChanged(QgsFeatureId id) const
Returns true if the specified feature ID has had its geometry changed but not committed.
void setAreaUnits(QgsUnitTypes::AreaUnit unit)
Sets the desired areal units for calculations involving geomCalculator(), e.g., "$area".
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
void setGeomCalculator(const QgsDistanceArea *calc)
Sets the geometry calculator used for distance and area calculations in expressions.
This is a container for configuration of the attribute table. The configuration is specific for one v...
QgsFields fields() const FINAL
Returns the list of fields of this layer.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
This class wraps a request for features to a vector layer (or directly its vector data provider).
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
Qt::ItemFlags flags(const QModelIndex &index) const override
Returns item flags for the index.
void featuresFiltered()
Emitted when the filtering of the features has been done.
@ Action
This column represents an action widget.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
QgsFeatureId rowToId(int row) const
Maps row to feature id.
void generateListOfVisibleFeatures()
Updates the list of currently visible features on the map canvas.
void sortColumnChanged(int column, Qt::SortOrder order)
Emitted whenever the sort column is changed.
void setExtent(const QgsRectangle &extent)
When rendering a map layer, calling this method sets the "clipping" extent for the layer (in the laye...
QgsVectorLayer * layer() const
Returns the layer this filter acts on.
QModelIndexList fidToIndexList(QgsFeatureId fid)
A model backed by a QgsVectorLayerCache which is able to provide feature/attribute information to a Q...
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant &value)
Emitted whenever an attribute value change is done in the edit buffer.
QVector< QgsAttributeTableConfig::ColumnConfig > columns() const
Gets the list with all columns and their configuration.
const Q_INVOKABLE QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
void extentsChanged()
Emitted when the extents of the map change.
QModelIndex fidToIndex(QgsFeatureId fid) override
QgsAttributeTableModel * masterModel() const
Returns the table model this filter is using.
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
void prefetchSortData(const QString &expression, unsigned long cacheIndex=0)
Prefetches the entire data for an expression.
Qt::ItemFlags flags(const QModelIndex &index) 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 setSelectedOnTop(bool selectedOnTop)
Changes the sort order of the features.
QgsFeatureId rowToId(const QModelIndex &row)
Returns the feature id for a given model index.
QVariant data(const QModelIndex &index, int role) const override
double scale() const
Returns the calculated map scale.
int extraColumns() const
Empty extra columns to announce from this model.
QgsVectorLayer * layer() const
Returns the layer this model uses as backend.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
QVariant headerData(int section, Qt::Orientation orientation, int role) const override
void prefetchColumnData(int column)
Caches the entire data for one column.
@ TypeRole
The type of a given column.
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override
Returns true if the source row will be accepted.
QSet< QgsFeatureId > QgsFeatureIds
bool selectedOnTop()
Returns if selected features are currently shown on top.
Qgis::SpatialFilterType spatialFilterType() const
Returns the spatial filter type which is currently set on this request.
QVariant evaluate()
Evaluate the feature and return the result.
void filterError(const QString &errorMessage)
Emitted when an error occurred while filtering features.
QString sortCacheExpression(unsigned long cacheIndex=0) const
The expression which was used to fill the sorting cache at index cacheIndex.
void setRendererScale(double scale)
Sets the renderer map scale.
@ FeatureIdRole
Get the feature id of the feature in this row.
void setFilterMode(FilterMode filterMode)
Set the filter mode the filter will use.
void disconnectFilterModeConnections()
Disconnect the connections set for the current filterMode.
bool isFeatureAdded(QgsFeatureId id) const
Returns true if the specified feature ID has been added but not committed.
QModelIndex mapToSource(const QModelIndex &proxyIndex) const override
QModelIndex mapFromMaster(const QModelIndex &sourceIndex) const
@ ColumnTypeActionButton
This column shows action buttons.
@ ShowSelected
Show only selected features.
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override
bool nextFeature(QgsFeature &f)
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...
void filterFeatures()
Updates the filtered features in the filter model.
@ ScaleDependent
Depends on scale if feature will be rendered (rule based )
void geometryChanged(QgsFeatureId fid, const QgsGeometry &geometry)
Emitted whenever a geometry change is done in the edit buffer.
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override
Used by the sorting algorithm.
@ BoundingBox
Filter using a bounding box.
QgsAttributeTableFilterModel(QgsMapCanvas *canvas, QgsAttributeTableModel *sourceModel, QObject *parent=nullptr)
Make sure, the master model is already loaded, so the selection will get synchronized.
virtual void setFilteredFeatures(const QgsFeatureIds &ids)
Specify a list of features, which the filter will accept.
int actionColumnIndex() const
Gets the index of the first column that contains an action widget.
bool needsGeometry() const
Returns true if the expression uses feature geometry for some computation.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
FilterMode filterMode()
The current filterModel.
@ SortRole
Role used for sorting start here.
int columnCount(const QModelIndex &parent=QModelIndex()) const override
Returns the number of columns.
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
const QgsFeatureRequest & request() const
Gets the the feature request.
Class for parsing and evaluation of expressions (formerly called "search strings")....
The QgsMapSettings class contains configuration for rendering of the map. The rendering itself is don...
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes output image size into account.
bool hasSameColumns(const QgsAttributeTableConfig &other) const
Compare this configuration's columns name, type, and order to other.
FilterMode
The filter mode defines how the rows should be filtered.
Wrapper for iterator of features from vector data provider or vector layer.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
const QgsMapToPixel & mapToPixel() const
QgsVectorLayerCache * layerCache() const
Returns the layer cache this model uses as backend.
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...
@ ShowVisible
Show only visible features (depends on the map canvas)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void update(const QgsFields &fields)
Update the configuration with the given fields.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer.