16#include <QItemSelectionModel> 
   17#include <QApplication> 
   21#include "moc_qgsattributetablefiltermodel.cpp" 
   41  : QSortFilterProxyModel( parent )
 
   45  setDynamicSortFilter( 
true );
 
   49  mReloadVisibleTimer.setSingleShot( 
true );
 
   50  connect( &mReloadVisibleTimer, &QTimer::timeout, 
this, &QgsAttributeTableFilterModel::reloadVisible );
 
   51  mFilterFeaturesTimer.setSingleShot( 
true );
 
 
   62    if ( leftSelected && !rightSelected )
 
   64      return sortOrder() == Qt::AscendingOrder;
 
   66    else if ( rightSelected && !leftSelected )
 
   68      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" );
 
  124      const int sourceSection = mapColumnToSource( section );
 
  125      return sourceModel()->headerData( sourceSection, orientation, role );
 
  130    if ( role == Qt::DisplayRole )
 
  134      const int sourceSection = 
mapToSource( index( section, ( !mColumnMapping.isEmpty() && mColumnMapping.at( 0 ) == -1 ) ? 1 : 0 ) ).row();
 
  135      return sourceModel()->headerData( sourceSection, orientation, role );
 
 
  142  return mColumnMapping.indexOf( -1 );
 
 
  148  return mColumnMapping.count();
 
 
  162  QVector<int> newColumnMapping;
 
  163  const auto constColumns = mConfig.
columns();
 
  167    if ( columnConfig.hidden )
 
  172    newColumnMapping << newValue;
 
  175  if ( newColumnMapping != mColumnMapping )
 
  177    bool requiresReset = 
false;
 
  178    int firstRemovedColumn = -1;
 
  179    int removedColumnCount = 0;
 
  182    for ( 
int i = 0; i < std::min( newColumnMapping.size(), mColumnMapping.size() - removedColumnCount ); ++i )
 
  184      if ( newColumnMapping.at( i ) == mColumnMapping.at( i + removedColumnCount ) )
 
  187      if ( firstRemovedColumn == -1 )
 
  189        firstRemovedColumn = i;
 
  191        while ( i < mColumnMapping.size() - removedColumnCount && mColumnMapping.at( i + removedColumnCount ) != newColumnMapping.at( i ) )
 
  193          ++removedColumnCount;
 
  198        requiresReset = 
true;
 
  204    if ( firstRemovedColumn == -1 )
 
  206      if ( newColumnMapping.size() > mColumnMapping.size() )
 
  209        beginInsertColumns( QModelIndex(), mColumnMapping.size(), newColumnMapping.size() - 1 );
 
  210        mColumnMapping = newColumnMapping;
 
  216        beginRemoveColumns( QModelIndex(), newColumnMapping.size(), mColumnMapping.size() - 1 );
 
  217        mColumnMapping = newColumnMapping;
 
  223      if ( newColumnMapping.size() == mColumnMapping.size() - removedColumnCount )
 
  226        beginRemoveColumns( QModelIndex(), firstRemovedColumn, firstRemovedColumn + removedColumnCount - 1 );
 
  227        mColumnMapping = newColumnMapping;
 
  232        requiresReset = 
true;
 
  239      mColumnMapping = newColumnMapping;
 
 
  250  mFilterExpression = expression;
 
  251  mFilterExpressionContext = context;
 
 
  256  if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
 
  257    order = Qt::AscendingOrder;
 
  259  QSortFilterProxyModel::sort( -1 );
 
  261  QSortFilterProxyModel::sort( 0, order );
 
 
  274    int column = sortColumn();
 
  275    Qt::SortOrder order = sortOrder();
 
  281    if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
 
  282      order = Qt::AscendingOrder;
 
  284    sort( column, order );
 
 
  291  mTableModel = sourceModel;
 
  295    mColumnMapping.append( i );
 
  298  QSortFilterProxyModel::setSourceModel( sourceModel );
 
  301  disconnect( mTableModel, SIGNAL( columnsAboutToBeInserted( QModelIndex, 
int, 
int ) ), 
this, SLOT( _q_sourceColumnsAboutToBeInserted( QModelIndex, 
int, 
int ) ) );
 
  302  disconnect( mTableModel, SIGNAL( columnsInserted( QModelIndex, 
int, 
int ) ), 
this, SLOT( _q_sourceColumnsInserted( QModelIndex, 
int, 
int ) ) );
 
  303  disconnect( mTableModel, SIGNAL( columnsAboutToBeRemoved( QModelIndex, 
int, 
int ) ), 
this, SLOT( _q_sourceColumnsAboutToBeRemoved( QModelIndex, 
int, 
int ) ) );
 
  304  disconnect( mTableModel, SIGNAL( columnsRemoved( QModelIndex, 
int, 
int ) ), 
this, SLOT( _q_sourceColumnsRemoved( QModelIndex, 
int, 
int ) ) );
 
  306  connect( mTableModel, &QAbstractItemModel::columnsAboutToBeInserted, 
this, &QgsAttributeTableFilterModel::onColumnsChanged );
 
  307  connect( mTableModel, &QAbstractItemModel::columnsAboutToBeRemoved, 
this, &QgsAttributeTableFilterModel::onColumnsChanged );
 
 
  312  return mSelectedOnTop;
 
 
  317  mFilteredFeatures = ids;
 
 
  328  ids.reserve( rowCount() );
 
  329  for ( 
int i = 0; i < rowCount(); ++i )
 
  331    const QModelIndex row = index( i, 0 );
 
 
  356  switch ( mFilterMode )
 
 
  404  Q_UNUSED( sourceParent )
 
  405  switch ( mFilterMode )
 
 
  453void QgsAttributeTableFilterModel::reloadVisible()
 
  460void QgsAttributeTableFilterModel::onAttributeValueChanged( 
QgsFeatureId fid, 
int idx, 
const QVariant &value )
 
  467    startTimedFilterFeatures();
 
  471void QgsAttributeTableFilterModel::onGeometryChanged()
 
  475    startTimedFilterFeatures();
 
  479void QgsAttributeTableFilterModel::startTimedReloadVisible()
 
  481  mReloadVisibleTimer.start( 10 );
 
  484void QgsAttributeTableFilterModel::startTimedFilterFeatures()
 
  486  mFilterFeaturesTimer.start( 10 );
 
  491  if ( !mFilterExpression.
isValid() )
 
  502  QApplication::setOverrideCursor( Qt::WaitCursor );
 
  528    if ( mFilterExpression.
evaluate( &mFilterExpressionContext ).toInt() != 0 )
 
  532    if ( mFilterExpression.
hasEvalError() && error.isEmpty() )
 
  542  QApplication::restoreOverrideCursor();
 
  546  if ( !error.isEmpty() )
 
 
  553void QgsAttributeTableFilterModel::selectionChanged()
 
  559  else if ( mSelectedOnTop )
 
  565void QgsAttributeTableFilterModel::onColumnsChanged()
 
  570int QgsAttributeTableFilterModel::mapColumnToSource( 
int column )
 const 
  572  if ( mColumnMapping.isEmpty() )
 
  574  if ( column < 0 || column >= mColumnMapping.size() )
 
  577    return mColumnMapping.at( column );
 
  580int QgsAttributeTableFilterModel::mapColumnFromSource( 
int column )
 const 
  582  if ( mColumnMapping.isEmpty() )
 
  585    return mColumnMapping.indexOf( column );
 
  598  mFilteredFeatures.clear();
 
  599  if ( !
layer()->renderer() )
 
  605  std::unique_ptr<QgsFeatureRenderer> renderer( 
layer()->renderer()->clone() );
 
  628  renderer->startRender( renderContext, 
layer()->fields() );
 
  641  if ( canvasFilter == QLatin1String( 
"FALSE" ) )
 
  643  if ( !canvasFilter.isEmpty() )
 
  653    if ( !filter || renderer->willRenderFeature( f, renderContext ) )
 
  655      mFilteredFeatures << f.
id();
 
  658    if ( t.elapsed() > 5000 )
 
  661      emit progress( i, cancel );
 
  674    renderer->stopRender( renderContext );
 
 
  690  QModelIndexList indexes;
 
  692  for ( 
const QModelIndex &idx : constIdToIndexList )
 
 
  702  if ( !proxyIndex.isValid() )
 
  703    return QModelIndex();
 
  705  int sourceColumn = mapColumnToSource( proxyIndex.column() );
 
  708  if ( sourceColumn == -1 )
 
  709    return QModelIndex();
 
  711  return QSortFilterProxyModel::mapToSource( index( proxyIndex.row(), sourceColumn, proxyIndex.parent() ) );
 
 
  716  const QModelIndex proxyIndex = QSortFilterProxyModel::mapFromSource( sourceIndex );
 
  718  if ( proxyIndex.column() < 0 )
 
  719    return QModelIndex();
 
  721  int col = mapColumnFromSource( proxyIndex.column() );
 
  726  return index( proxyIndex.row(), col, proxyIndex.parent() );
 
 
  732  if ( mapColumnToSource( index.column() ) == -1 )
 
  733    return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
 
  735  const QModelIndex source_index = 
mapToSource( index );
 
 
  741  if ( !proxyIndex.isValid() )
 
  742    return QModelIndex();
 
  744  int sourceColumn = mapColumnToSource( proxyIndex.column() );
 
  748  if ( sourceColumn == -1 )
 
  751  return QSortFilterProxyModel::mapToSource( index( proxyIndex.row(), sourceColumn, proxyIndex.parent() ) );
 
 
@ 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.
 
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
 
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(FilterMode 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.
 
@ 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.
 
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.
 
@ ShowInvalid
Show only features not respecting constraints.
 
@ 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.
 
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
 
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.
 
QgsFeatureIds filteredFeatures()
Gets a list of currently filtered feature ids.
 
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.
 
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.
 
QString sortCacheExpression(unsigned long cacheIndex=0) const
The expression which was used to fill the sorting cache at index cacheIndex.
 
QgsVectorLayer * layer() const
Returns the layer this model uses as backend.
 
int extraColumns() const
Empty extra columns to announce from this model.
 
QgsVectorLayerCache * layerCache() const
Returns the layer cache this model uses as backend.
 
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.
 
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").
 
QString evalErrorString() const
Returns evaluation error.
 
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
 
void setDistanceUnits(Qgis::DistanceUnit unit)
Sets the desired distance units for calculations involving geomCalculator(), e.g.,...
 
void setAreaUnits(Qgis::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)
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.
 
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
 
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.
 
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.
 
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.
 
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
 
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.