QGIS API Documentation 3.40.0-Bratislava (b56115d8743)
Loading...
Searching...
No Matches
qgsattributetablefiltermodel.cpp
Go to the documentation of this file.
1/***************************************************************************
2 QgsAttributeTableFilterModel.cpp
3 --------------------------------------
4 Date : Feb 2009
5 Copyright : (C) 2009 Vita Cizek
6 Email : weetya (at) gmail.com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include <QItemSelectionModel>
17#include <QApplication>
18
19#include "qgis.h"
22#include "qgsfeatureiterator.h"
23#include "qgsvectorlayer.h"
25#include "qgsfeature.h"
26#include "qgsmapcanvas.h"
27#include "qgslogger.h"
28#include "qgsrenderer.h"
31#include "qgsvectorlayercache.h"
32#include "qgsrendercontext.h"
33#include "qgsmapcanvasutils.h"
34
36// Filter Model //
38
40 : QSortFilterProxyModel( parent )
41 , mCanvas( canvas )
42{
43 setSourceModel( sourceModel );
44 setDynamicSortFilter( true );
45 setSortRole( static_cast< int >( QgsAttributeTableModel::CustomRole::Sort ) );
46 connect( layer(), &QgsVectorLayer::selectionChanged, this, &QgsAttributeTableFilterModel::selectionChanged );
47
48 mReloadVisibleTimer.setSingleShot( true );
49 connect( &mReloadVisibleTimer, &QTimer::timeout, this, &QgsAttributeTableFilterModel::reloadVisible );
50 mFilterFeaturesTimer.setSingleShot( true );
51 connect( &mFilterFeaturesTimer, &QTimer::timeout, this, &QgsAttributeTableFilterModel::filterFeatures );
52}
53
54bool QgsAttributeTableFilterModel::lessThan( const QModelIndex &left, const QModelIndex &right ) const
55{
56 if ( mSelectedOnTop )
57 {
58 const bool leftSelected = layer()->selectedFeatureIds().contains( masterModel()->rowToId( left.row() ) );
59 const bool rightSelected = layer()->selectedFeatureIds().contains( masterModel()->rowToId( right.row() ) );
60
61 if ( leftSelected && !rightSelected )
62 {
63 return sortOrder() == Qt::AscendingOrder;
64 }
65 else if ( rightSelected && !leftSelected )
66 {
67 return sortOrder() == Qt::DescendingOrder;
68 }
69 }
70
71 if ( mTableModel->sortCacheExpression().isEmpty() )
72 {
73 //shortcut when no sort order set
74 return false;
75 }
76
77 return qgsVariantLessThan( left.data( static_cast< int >( QgsAttributeTableModel::CustomRole::Sort ) ),
78 right.data( static_cast< int >( QgsAttributeTableModel::CustomRole::Sort ) ) );
79}
80
81void QgsAttributeTableFilterModel::sort( int column, Qt::SortOrder order )
82{
83 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
84 order = Qt::AscendingOrder;
85 if ( column < 0 || column >= mColumnMapping.size() )
86 {
87 sort( QString() );
88 }
89 else
90 {
91 const int myColumn = mColumnMapping.at( column );
92 masterModel()->prefetchColumnData( myColumn );
93 QSortFilterProxyModel::sort( myColumn, order );
94 }
95 emit sortColumnChanged( column, order );
96}
97
98QVariant QgsAttributeTableFilterModel::data( const QModelIndex &index, int role ) const
99{
100 if ( mapColumnToSource( index.column() ) == -1 ) // actions
101 {
102 if ( role == static_cast< int >( CustomRole::Type ) )
104 else if ( role == static_cast< int >( QgsAttributeTableModel::CustomRole::FeatureId ) )
105 {
106 const QModelIndex fieldIndex = QSortFilterProxyModel::mapToSource( QSortFilterProxyModel::index( index.row(), 0, index.parent() ) );
107 return sourceModel()->data( fieldIndex, static_cast< int >( QgsAttributeTableModel::CustomRole::FeatureId ) );
108 }
109 }
110 else if ( role == static_cast< int >( CustomRole::Type ) )
111 return ColumnTypeField;
112
113 return QSortFilterProxyModel::data( index, role );
114}
115
116QVariant QgsAttributeTableFilterModel::headerData( int section, Qt::Orientation orientation, int role ) const
117{
118 if ( orientation == Qt::Horizontal )
119 {
120 if ( mColumnMapping.at( section ) == -1 && role == Qt::DisplayRole )
121 return tr( "Actions" );
122 else
123 {
124 const int sourceSection = mapColumnToSource( section );
125 return sourceModel()->headerData( sourceSection, orientation, role );
126 }
127 }
128 else
129 {
130 if ( role == Qt::DisplayRole )
131 return section + 1;
132 else
133 {
134 const int sourceSection = mapToSource( index( section, ( !mColumnMapping.isEmpty() && mColumnMapping.at( 0 ) == -1 ) ? 1 : 0 ) ).row();
135 return sourceModel()->headerData( sourceSection, orientation, role );
136 }
137 }
138}
139
141{
142 return mColumnMapping.indexOf( -1 );
143}
144
145int QgsAttributeTableFilterModel::columnCount( const QModelIndex &parent ) const
146{
147 Q_UNUSED( parent )
148 return mColumnMapping.count();
149}
150
152{
153 const QgsAttributeTableConfig oldConfig = mConfig;
154 mConfig = config;
155 mConfig.update( layer()->fields() );
156
157 if ( !force && mConfig.hasSameColumns( oldConfig ) )
158 {
159 return;
160 }
161
162 QVector<int> newColumnMapping;
163 const auto constColumns = mConfig.columns();
164 for ( const QgsAttributeTableConfig::ColumnConfig &columnConfig : constColumns )
165 {
166 // Hidden? Forget about this column
167 if ( columnConfig.hidden )
168 continue;
169
170 // The new value for the mapping (field index or -1 for action column)
171 const int newValue = ( columnConfig.type == QgsAttributeTableConfig::Action ) ? -1 : layer()->fields().lookupField( columnConfig.name );
172 newColumnMapping << newValue;
173 }
174
175 if ( newColumnMapping != mColumnMapping )
176 {
177 bool requiresReset = false;
178 int firstRemovedColumn = -1;
179 int removedColumnCount = 0;
180
181 // Check if there have a contiguous set of columns have been removed or if we require a full reset
182 for ( int i = 0; i < std::min( newColumnMapping.size(), mColumnMapping.size() - removedColumnCount ); ++i )
183 {
184 if ( newColumnMapping.at( i ) == mColumnMapping.at( i + removedColumnCount ) )
185 continue;
186
187 if ( firstRemovedColumn == -1 )
188 {
189 firstRemovedColumn = i;
190
191 while ( i < mColumnMapping.size() - removedColumnCount && mColumnMapping.at( i + removedColumnCount ) != newColumnMapping.at( i ) )
192 {
193 ++removedColumnCount;
194 }
195 }
196 else
197 {
198 requiresReset = true;
199 break;
200 }
201 }
202
203 // No difference found so far
204 if ( firstRemovedColumn == -1 )
205 {
206 if ( newColumnMapping.size() > mColumnMapping.size() )
207 {
208 // More columns: appended to the end
209 beginInsertColumns( QModelIndex(), mColumnMapping.size(), newColumnMapping.size() - 1 );
210 mColumnMapping = newColumnMapping;
211 endInsertColumns();
212 }
213 else
214 {
215 // Less columns: removed from the end
216 beginRemoveColumns( QModelIndex(), newColumnMapping.size(), mColumnMapping.size() - 1 );
217 mColumnMapping = newColumnMapping;
218 endRemoveColumns();
219 }
220 }
221 else
222 {
223 if ( newColumnMapping.size() == mColumnMapping.size() - removedColumnCount )
224 {
225 //the amount of removed column in the model need to be equal removedColumnCount
226 beginRemoveColumns( QModelIndex(), firstRemovedColumn, firstRemovedColumn + removedColumnCount - 1 );
227 mColumnMapping = newColumnMapping;
228 endRemoveColumns();
229 }
230 else
231 {
232 requiresReset = true;
233 }
234 }
235
236 if ( requiresReset )
237 {
238 beginResetModel();
239 mColumnMapping = newColumnMapping;
240 endResetModel();
241 }
242 }
243
244 if ( !config.sortExpression().isEmpty() )
245 sort( config.sortExpression(), config.sortOrder() );
246}
247
249{
250 mFilterExpression = expression;
251 mFilterExpressionContext = context;
252}
253
254void QgsAttributeTableFilterModel::sort( const QString &expression, Qt::SortOrder order )
255{
256 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
257 order = Qt::AscendingOrder;
258
259 QSortFilterProxyModel::sort( -1 );
260 masterModel()->prefetchSortData( expression );
261 QSortFilterProxyModel::sort( 0, order );
262}
263
268
270{
271 if ( mSelectedOnTop != selectedOnTop )
272 {
273 mSelectedOnTop = selectedOnTop;
274 int column = sortColumn();
275 Qt::SortOrder order = sortOrder();
276
277 // set default sort values if they are not correctly set
278 if ( column < 0 )
279 column = 0;
280
281 if ( order != Qt::AscendingOrder && order != Qt::DescendingOrder )
282 order = Qt::AscendingOrder;
283
284 sort( column, order );
285 invalidate();
286 }
287}
288
290{
291 mTableModel = sourceModel;
292
293 for ( int i = 0; i < mTableModel->columnCount() - mTableModel->extraColumns(); ++i )
294 {
295 mColumnMapping.append( i );
296 }
297
298 QSortFilterProxyModel::setSourceModel( sourceModel );
299
300 // Disconnect any code to update columns in the parent, we handle this manually
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 ) ) );
305 // The following connections are needed in order to keep the filter model in sync, see: regression #15974
306 connect( mTableModel, &QAbstractItemModel::columnsAboutToBeInserted, this, &QgsAttributeTableFilterModel::onColumnsChanged );
307 connect( mTableModel, &QAbstractItemModel::columnsAboutToBeRemoved, this, &QgsAttributeTableFilterModel::onColumnsChanged );
308
309}
310
312{
313 return mSelectedOnTop;
314}
315
317{
318 mFilteredFeatures = ids;
319 if ( mFilterMode != ShowFilteredList &&
320 mFilterMode != ShowInvalid )
321 {
323 }
324 invalidateFilter();
325}
326
328{
329 QgsFeatureIds ids;
330 ids.reserve( rowCount() );
331 for ( int i = 0; i < rowCount(); ++i )
332 {
333 const QModelIndex row = index( i, 0 );
334 ids << rowToId( row );
335 }
336 return ids;
337}
338
340{
341 if ( filterMode != mFilterMode )
342 {
345 mFilterMode = filterMode;
346 invalidate();
347
349 {
351 }
352 }
353}
354
356{
357 // cleanup existing connections
358 switch ( mFilterMode )
359 {
360 case ShowVisible:
361 disconnect( mCanvas, &QgsMapCanvas::extentsChanged, this, &QgsAttributeTableFilterModel::startTimedReloadVisible );
362 disconnect( mCanvas, &QgsMapCanvas::temporalRangeChanged, this, &QgsAttributeTableFilterModel::startTimedReloadVisible );
363 disconnect( layer(), &QgsVectorLayer::featureAdded, this, &QgsAttributeTableFilterModel::startTimedReloadVisible );
364 disconnect( layer(), &QgsVectorLayer::geometryChanged, this, &QgsAttributeTableFilterModel::startTimedReloadVisible );
365 break;
366 case ShowAll:
367 case ShowEdited:
368 case ShowSelected:
369 break;
370 case ShowFilteredList:
371 case ShowInvalid:
372 disconnect( layer(), &QgsVectorLayer::featureAdded, this, &QgsAttributeTableFilterModel::startTimedFilterFeatures );
373 disconnect( layer(), &QgsVectorLayer::attributeValueChanged, this, &QgsAttributeTableFilterModel::onAttributeValueChanged );
374 disconnect( layer(), &QgsVectorLayer::geometryChanged, this, &QgsAttributeTableFilterModel::onGeometryChanged );
375 break;
376 }
377}
378
380{
381 // setup new connections
382 switch ( filterMode )
383 {
384 case ShowVisible:
385 connect( mCanvas, &QgsMapCanvas::extentsChanged, this, &QgsAttributeTableFilterModel::startTimedReloadVisible );
386 connect( mCanvas, &QgsMapCanvas::temporalRangeChanged, this, &QgsAttributeTableFilterModel::startTimedReloadVisible );
387 connect( layer(), &QgsVectorLayer::featureAdded, this, &QgsAttributeTableFilterModel::startTimedReloadVisible );
388 connect( layer(), &QgsVectorLayer::geometryChanged, this, &QgsAttributeTableFilterModel::startTimedReloadVisible );
390 break;
391 case ShowAll:
392 case ShowEdited:
393 case ShowSelected:
394 break;
395 case ShowFilteredList:
396 case ShowInvalid:
397 connect( layer(), &QgsVectorLayer::featureAdded, this, &QgsAttributeTableFilterModel::startTimedFilterFeatures );
398 connect( layer(), &QgsVectorLayer::attributeValueChanged, this, &QgsAttributeTableFilterModel::onAttributeValueChanged );
399 connect( layer(), &QgsVectorLayer::geometryChanged, this, &QgsAttributeTableFilterModel::onGeometryChanged );
400 break;
401 }
402}
403
404bool QgsAttributeTableFilterModel::filterAcceptsRow( int sourceRow, const QModelIndex &sourceParent ) const
405{
406 Q_UNUSED( sourceParent )
407 switch ( mFilterMode )
408 {
409 case ShowAll:
410 return true;
411
412 case ShowFilteredList:
413 case ShowInvalid:
414 return mFilteredFeatures.contains( masterModel()->rowToId( sourceRow ) );
415
416 case ShowSelected:
417 return layer()->selectedFeatureIds().contains( masterModel()->rowToId( sourceRow ) );
418
419 case ShowVisible:
420 return mFilteredFeatures.contains( masterModel()->rowToId( sourceRow ) );
421
422 case ShowEdited:
423 {
424 QgsVectorLayerEditBuffer *editBuffer = layer()->editBuffer();
425 if ( editBuffer )
426 {
427 const QgsFeatureId fid = masterModel()->rowToId( sourceRow );
428
429 if ( editBuffer->isFeatureAdded( fid ) )
430 return true;
431
432 if ( editBuffer->isFeatureAttributesChanged( fid ) )
433 return true;
434
435 if ( editBuffer->isFeatureGeometryChanged( fid ) )
436 return true;
437
438 return false;
439 }
440 return false;
441 }
442
443 default:
444 Q_ASSERT( false ); // In debug mode complain
445 return true; // In release mode accept row
446 }
447 // returns are handled in their respective case statement above
448}
449
451{
452 reloadVisible();
453}
454
455void QgsAttributeTableFilterModel::reloadVisible()
456{
458 invalidateFilter();
459 emit visibleReloaded();
460}
461
462void QgsAttributeTableFilterModel::onAttributeValueChanged( QgsFeatureId fid, int idx, const QVariant &value )
463{
464 Q_UNUSED( fid );
465 Q_UNUSED( value );
466
467 if ( mFilterMode == QgsAttributeTableFilterModel::ShowInvalid || mFilterExpression.referencedAttributeIndexes( layer()->fields() ).contains( idx ) )
468 {
469 startTimedFilterFeatures();
470 }
471}
472
473void QgsAttributeTableFilterModel::onGeometryChanged()
474{
475 if ( mFilterMode == QgsAttributeTableFilterModel::ShowInvalid || mFilterExpression.needsGeometry() )
476 {
477 startTimedFilterFeatures();
478 }
479}
480
481void QgsAttributeTableFilterModel::startTimedReloadVisible()
482{
483 mReloadVisibleTimer.start( 10 );
484}
485
486void QgsAttributeTableFilterModel::startTimedFilterFeatures()
487{
488 mFilterFeaturesTimer.start( 10 );
489}
490
492{
493 if ( !mFilterExpression.isValid() )
494 return;
495
497 QgsDistanceArea distanceArea;
498
499 distanceArea.setSourceCrs( mTableModel->layer()->crs(), QgsProject::instance()->transformContext() );
500 distanceArea.setEllipsoid( QgsProject::instance()->ellipsoid() );
501
502 const bool fetchGeom = mFilterExpression.needsGeometry();
503
504 QApplication::setOverrideCursor( Qt::WaitCursor );
505
506 mFilterExpression.setGeomCalculator( &distanceArea );
507 mFilterExpression.setDistanceUnits( QgsProject::instance()->distanceUnits() );
508 mFilterExpression.setAreaUnits( QgsProject::instance()->areaUnits() );
509 QgsFeatureRequest request( mTableModel->request() );
510 request.setSubsetOfAttributes( mFilterExpression.referencedColumns(), mTableModel->layer()->fields() );
511 if ( !fetchGeom )
512 {
514 }
515 else
516 {
517 // force geometry extraction if the filter requests it
518 request.setFlags( request.flags() & ~static_cast<int>( Qgis::FeatureRequestFlag::NoGeometry ) );
519 }
520 QgsFeatureIterator featIt = mTableModel->layer()->getFeatures( request );
521
522 QgsFeature f;
523
524 // Record the first evaluation error
525 QString error;
526
527 while ( featIt.nextFeature( f ) )
528 {
529 mFilterExpressionContext.setFeature( f );
530 if ( mFilterExpression.evaluate( &mFilterExpressionContext ).toInt() != 0 )
531 filteredFeatures << f.id();
532
533 // check if there were errors during evaluating
534 if ( mFilterExpression.hasEvalError() && error.isEmpty() )
535 {
536 error = mFilterExpression.evalErrorString( );
537 }
538 }
539
540 featIt.close();
541
543
544 QApplication::restoreOverrideCursor();
545
546 emit featuresFiltered();
547
548 if ( ! error.isEmpty() )
549 {
550 emit filterError( error );
551 }
552
553}
554
555
556void QgsAttributeTableFilterModel::selectionChanged()
557{
558 if ( ShowSelected == mFilterMode )
559 {
560 invalidateFilter();
561 }
562 else if ( mSelectedOnTop )
563 {
564 invalidate();
565 }
566}
567
568void QgsAttributeTableFilterModel::onColumnsChanged()
569{
570 setAttributeTableConfig( mConfig );
571}
572
573int QgsAttributeTableFilterModel::mapColumnToSource( int column ) const
574{
575 if ( mColumnMapping.isEmpty() )
576 return column;
577 if ( column < 0 || column >= mColumnMapping.size() )
578 return -1;
579 else
580 return mColumnMapping.at( column );
581}
582
583int QgsAttributeTableFilterModel::mapColumnFromSource( int column ) const
584{
585 if ( mColumnMapping.isEmpty() )
586 return column;
587 else
588 return mColumnMapping.indexOf( column );
589}
590
592{
593 if ( !layer() )
594 return;
595
596 bool filter = false;
597 const QgsRectangle rect = mCanvas->mapSettings().mapToLayerCoordinates( layer(), mCanvas->extent() );
598 QgsRenderContext renderContext;
600
601 mFilteredFeatures.clear();
602 if ( !layer()->renderer() )
603 {
604 QgsDebugError( QStringLiteral( "Cannot get renderer" ) );
605 return;
606 }
607
608 std::unique_ptr< QgsFeatureRenderer > renderer( layer()->renderer()->clone() );
609
610 const QgsMapSettings &ms = mCanvas->mapSettings();
611 if ( !layer()->isInScaleRange( ms.scale() ) )
612 {
613 QgsDebugMsgLevel( QStringLiteral( "Out of scale limits" ), 2 );
614 }
615 else
616 {
617 if ( renderer->capabilities() & QgsFeatureRenderer::ScaleDependent )
618 {
619 // setup scale
620 // mapRenderer()->renderContext()->scale is not automatically updated when
621 // render extent changes (because it's scale is used to identify if changed
622 // since last render) -> use local context
623 renderContext.setExtent( ms.visibleExtent() );
624 renderContext.setMapToPixel( ms.mapToPixel() );
625 renderContext.setRendererScale( ms.scale() );
626 }
627
628 filter = renderer->capabilities() & QgsFeatureRenderer::Filter;
629 }
630
631 renderer->startRender( renderContext, layer()->fields() );
632
633 QgsFeatureRequest r( masterModel()->request() );
635 {
636 r.setFilterRect( r.filterRect().intersect( rect ) );
637 }
638 else
639 {
640 r.setFilterRect( rect );
641 }
642
643 const QString canvasFilter = QgsMapCanvasUtils::filterForLayer( mCanvas, layer() );
644 if ( canvasFilter == QLatin1String( "FALSE" ) )
645 return;
646 if ( !canvasFilter.isEmpty() )
647 r.setFilterExpression( canvasFilter );
648
650
651 QgsFeature f;
652
653 while ( features.nextFeature( f ) )
654 {
655 renderContext.expressionContext().setFeature( f );
656 if ( !filter || renderer->willRenderFeature( f, renderContext ) )
657 {
658 mFilteredFeatures << f.id();
659 }
660#if 0
661 if ( t.elapsed() > 5000 )
662 {
663 bool cancel = false;
664 emit progress( i, cancel );
665 if ( cancel )
666 break;
667
668 t.restart();
669 }
670#endif
671 }
672
673 features.close();
674
675 if ( renderer->capabilities() & QgsFeatureRenderer::ScaleDependent )
676 {
677 renderer->stopRender( renderContext );
678 }
679}
680
682{
683 return masterModel()->rowToId( mapToSource( row ).row() );
684}
685
687{
688 return mapFromMaster( masterModel()->idToIndex( fid ) );
689}
690
692{
693 QModelIndexList indexes;
694 const auto constIdToIndexList = masterModel()->idToIndexList( fid );
695 for ( const QModelIndex &idx : constIdToIndexList )
696 {
697 indexes.append( mapFromMaster( idx ) );
698 }
699
700 return indexes;
701}
702
703QModelIndex QgsAttributeTableFilterModel::mapToSource( const QModelIndex &proxyIndex ) const
704{
705 if ( !proxyIndex.isValid() )
706 return QModelIndex();
707
708 int sourceColumn = mapColumnToSource( proxyIndex.column() );
709
710 // For the action column there is no matching column in the source model, just return invalid
711 if ( sourceColumn == -1 )
712 return QModelIndex();
713
714 return QSortFilterProxyModel::mapToSource( index( proxyIndex.row(), sourceColumn, proxyIndex.parent() ) );
715}
716
717QModelIndex QgsAttributeTableFilterModel::mapFromSource( const QModelIndex &sourceIndex ) const
718{
719 const QModelIndex proxyIndex = QSortFilterProxyModel::mapFromSource( sourceIndex );
720
721 if ( proxyIndex.column() < 0 )
722 return QModelIndex();
723
724 int col = mapColumnFromSource( proxyIndex.column() );
725
726 if ( col == -1 )
727 col = 0;
728
729 return index( proxyIndex.row(), col, proxyIndex.parent() );
730}
731
732Qt::ItemFlags QgsAttributeTableFilterModel::flags( const QModelIndex &index ) const
733{
734 // Handle the action column flags here, the master model doesn't know it
735 if ( mapColumnToSource( index.column() ) == -1 )
736 return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
737
738 const QModelIndex source_index = mapToSource( index );
739 return masterModel()->flags( source_index );
740}
741
742QModelIndex QgsAttributeTableFilterModel::mapToMaster( const QModelIndex &proxyIndex ) const
743{
744 if ( !proxyIndex.isValid() )
745 return QModelIndex();
746
747 int sourceColumn = mapColumnToSource( proxyIndex.column() );
748
749 // For the action column there is no matching column in the source model, just return the first one
750 // so we are still able to query for the feature id, the feature...
751 if ( sourceColumn == -1 )
752 sourceColumn = 0;
753
754 return QSortFilterProxyModel::mapToSource( index( proxyIndex.row(), sourceColumn, proxyIndex.parent() ) );
755}
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
@ BoundingBox
Filter using a bounding box.
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
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.
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.
Class for 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 ....
This class 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...
Definition qgsfeature.h:58
QgsFeatureId id
Definition qgsfeature.h:66
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
Definition qgsmaplayer.h:83
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 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
Definition qgsproject.h:113
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.
Definition qgis.cpp:120
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
#define QgsDebugError(str)
Definition qgslogger.h:38
Defines the configuration of a column in the attribute table.