QGIS API Documentation  2.99.0-Master (13a3f2f)
qgsattributetablemodel.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  QgsAttributeTableModel.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 "qgsapplication.h"
17 #include "qgsattributetablemodel.h"
19 
20 #include "qgsactionmanager.h"
22 #include "qgseditorwidgetfactory.h"
23 #include "qgsexpression.h"
24 #include "qgsfeatureiterator.h"
25 #include "qgsconditionalstyle.h"
26 #include "qgsfields.h"
27 #include "qgsfieldformatter.h"
28 #include "qgslogger.h"
29 #include "qgsmapcanvas.h"
31 #include "qgsrenderer.h"
32 #include "qgsvectorlayer.h"
33 #include "qgsvectordataprovider.h"
34 #include "qgssymbollayerutils.h"
36 #include "qgsgui.h"
37 #include "qgsexpressionnodeimpl.h"
38 
39 #include <QVariant>
40 
41 #include <limits>
42 
44  : QAbstractTableModel( parent )
45  , mLayerCache( layerCache )
46  , mFieldCount( 0 )
47  , mSortFieldIndex( -1 )
48  , mExtraColumns( 0 )
49 {
50  mExpressionContext.appendScopes( QgsExpressionContextUtils::globalProjectLayerScopes( layerCache->layer() ) );
51 
52  if ( layerCache->layer()->geometryType() == QgsWkbTypes::NullGeometry )
53  {
54  mFeatureRequest.setFlags( QgsFeatureRequest::NoGeometry );
55  }
56 
58 
59  if ( !layer()->hasGeometryType() )
60  mFeatureRequest.setFlags( QgsFeatureRequest::NoGeometry );
61 
62  loadAttributes();
63 
64  connect( mLayerCache, &QgsVectorLayerCache::attributeValueChanged, this, &QgsAttributeTableModel::attributeValueChanged );
65  connect( layer(), &QgsVectorLayer::featuresDeleted, this, &QgsAttributeTableModel::featuresDeleted );
66  connect( layer(), &QgsVectorLayer::attributeDeleted, this, &QgsAttributeTableModel::attributeDeleted );
67  connect( layer(), &QgsVectorLayer::updatedFields, this, &QgsAttributeTableModel::updatedFields );
68  connect( layer(), &QgsVectorLayer::editCommandEnded, this, &QgsAttributeTableModel::editCommandEnded );
69  connect( mLayerCache, &QgsVectorLayerCache::featureAdded, this, [ = ]( QgsFeatureId id ) { featureAdded( id ); } );
70  connect( mLayerCache, &QgsVectorLayerCache::cachedLayerDeleted, this, &QgsAttributeTableModel::layerDeleted );
71 }
72 
73 bool QgsAttributeTableModel::loadFeatureAtId( QgsFeatureId fid ) const
74 {
75  QgsDebugMsgLevel( QString( "loading feature %1" ).arg( fid ), 3 );
76 
77  if ( fid == std::numeric_limits<int>::min() )
78  {
79  return false;
80  }
81 
82  return mLayerCache->featureAtId( fid, mFeat );
83 }
84 
86 {
87  return mExtraColumns;
88 }
89 
91 {
92  mExtraColumns = extraColumns;
93  loadAttributes();
94 }
95 
96 void QgsAttributeTableModel::featuresDeleted( const QgsFeatureIds &fids )
97 {
98  QList<int> rows;
99 
100  Q_FOREACH ( QgsFeatureId fid, fids )
101  {
102  QgsDebugMsgLevel( QString( "(%2) fid: %1, size: %3" ).arg( fid ).arg( mFeatureRequest.filterType() ).arg( mIdRowMap.size() ), 4 );
103 
104  int row = idToRow( fid );
105  if ( row != -1 )
106  rows << row;
107  }
108 
109  std::sort( rows.begin(), rows.end() );
110 
111  int lastRow = -1;
112  int beginRow = -1;
113  int currentRowCount = 0;
114  int removedRows = 0;
115  bool reset = false;
116 
117  Q_FOREACH ( int row, rows )
118  {
119 #if 0
120  qDebug() << "Row: " << row << ", begin " << beginRow << ", last " << lastRow << ", current " << currentRowCount << ", removed " << removedRows;
121 #endif
122  if ( lastRow == -1 )
123  {
124  beginRow = row;
125  }
126 
127  if ( row != lastRow + 1 && lastRow != -1 )
128  {
129  if ( rows.count() > 100 && currentRowCount < 10 )
130  {
131  reset = true;
132  break;
133  }
134  removeRows( beginRow - removedRows, currentRowCount );
135 
136  beginRow = row;
137  removedRows += currentRowCount;
138  currentRowCount = 0;
139  }
140 
141  currentRowCount++;
142 
143  lastRow = row;
144  }
145 
146  if ( !reset )
147  removeRows( beginRow - removedRows, currentRowCount );
148  else
149  resetModel();
150 }
151 
152 bool QgsAttributeTableModel::removeRows( int row, int count, const QModelIndex &parent )
153 {
154 
155  if ( row < 0 || count < 1 )
156  return false;
157 
158  beginRemoveRows( parent, row, row + count - 1 );
159 
160 #ifdef QGISDEBUG
161  if ( 3 <= QgsLogger::debugLevel() )
162  QgsDebugMsgLevel( QString( "remove %2 rows at %1 (rows %3, ids %4)" ).arg( row ).arg( count ).arg( mRowIdMap.size() ).arg( mIdRowMap.size() ), 3 );
163 #endif
164 
165  // clean old references
166  for ( int i = row; i < row + count; i++ )
167  {
168  mSortCache.remove( mRowIdMap[i] );
169  mIdRowMap.remove( mRowIdMap[i] );
170  mRowIdMap.remove( i );
171  }
172 
173  // update maps
174  int n = mRowIdMap.size() + count;
175  for ( int i = row + count; i < n; i++ )
176  {
177  QgsFeatureId id = mRowIdMap[i];
178  mIdRowMap[id] -= count;
179  mRowIdMap[i - count] = id;
180  mRowIdMap.remove( i );
181  }
182 
183 #ifdef QGISDEBUG
184  if ( 4 <= QgsLogger::debugLevel() )
185  {
186  QgsDebugMsgLevel( QString( "after removal rows %1, ids %2" ).arg( mRowIdMap.size() ).arg( mIdRowMap.size() ), 4 );
187  QgsDebugMsgLevel( "id->row", 4 );
188  for ( QHash<QgsFeatureId, int>::const_iterator it = mIdRowMap.constBegin(); it != mIdRowMap.constEnd(); ++it )
189  QgsDebugMsgLevel( QString( "%1->%2" ).arg( FID_TO_STRING( it.key() ) ).arg( *it ), 4 );
190 
191  QgsDebugMsgLevel( "row->id", 4 );
192  for ( QHash<int, QgsFeatureId>::const_iterator it = mRowIdMap.constBegin(); it != mRowIdMap.constEnd(); ++it )
193  QgsDebugMsgLevel( QString( "%1->%2" ).arg( it.key() ).arg( FID_TO_STRING( *it ) ), 4 );
194  }
195 #endif
196 
197  Q_ASSERT( mRowIdMap.size() == mIdRowMap.size() );
198 
199  endRemoveRows();
200 
201  return true;
202 }
203 
204 void QgsAttributeTableModel::featureAdded( QgsFeatureId fid, bool resettingModel )
205 {
206  QgsDebugMsgLevel( QString( "(%2) fid: %1" ).arg( fid ).arg( mFeatureRequest.filterType() ), 4 );
207  bool featOk = true;
208 
209  if ( mFeat.id() != fid )
210  featOk = loadFeatureAtId( fid );
211 
212  if ( featOk && mFeatureRequest.acceptFeature( mFeat ) )
213  {
214  if ( mSortFieldIndex >= 0 )
215  {
216  QgsFieldFormatter *fieldFormatter = mFieldFormatters.at( mSortFieldIndex );
217  const QVariant &widgetCache = mAttributeWidgetCaches.at( mSortFieldIndex );
218  const QVariantMap &widgetConfig = mWidgetConfigs.at( mSortFieldIndex );
219  QVariant sortValue = fieldFormatter->representValue( layer(), mSortFieldIndex, widgetConfig, widgetCache, mFeat.attribute( mSortFieldIndex ) );
220  mSortCache.insert( mFeat.id(), sortValue );
221  }
222  else if ( mSortCacheExpression.isValid() )
223  {
224  mExpressionContext.setFeature( mFeat );
225  mSortCache[mFeat.id()] = mSortCacheExpression.evaluate( &mExpressionContext );
226  }
227 
228  // Skip if the fid is already in the map (do not add twice)!
229  if ( ! mIdRowMap.contains( fid ) )
230  {
231  int n = mRowIdMap.size();
232  if ( !resettingModel )
233  beginInsertRows( QModelIndex(), n, n );
234  mIdRowMap.insert( fid, n );
235  mRowIdMap.insert( n, fid );
236  if ( !resettingModel )
237  endInsertRows();
238  reload( index( rowCount() - 1, 0 ), index( rowCount() - 1, columnCount() ) );
239  }
240  }
241 }
242 
243 void QgsAttributeTableModel::updatedFields()
244 {
245  loadAttributes();
246  emit modelChanged();
247 }
248 
249 void QgsAttributeTableModel::editCommandEnded()
250 {
251  // do not do reload(...) due would trigger (dataChanged) row sort
252  // giving issue: https://issues.qgis.org/issues/15976
253  mChangedCellBounds = QRect();
254 }
255 
256 void QgsAttributeTableModel::attributeDeleted( int idx )
257 {
258  if ( mSortCacheAttributes.contains( idx ) )
259  prefetchSortData( QString() );
260 }
261 
262 void QgsAttributeTableModel::layerDeleted()
263 {
264  removeRows( 0, rowCount() );
265 
266  mAttributeWidgetCaches.clear();
267  mAttributes.clear();
268  mWidgetFactories.clear();
269  mWidgetConfigs.clear();
270  mFieldFormatters.clear();
271 }
272 
273 void QgsAttributeTableModel::fieldFormatterRemoved( QgsFieldFormatter *fieldFormatter )
274 {
275  for ( int i = 0; i < mFieldFormatters.size(); ++i )
276  {
277  if ( mFieldFormatters.at( i ) == fieldFormatter )
279  }
280 }
281 
282 void QgsAttributeTableModel::attributeValueChanged( QgsFeatureId fid, int idx, const QVariant &value )
283 {
284  QgsDebugMsgLevel( QString( "(%4) fid: %1, idx: %2, value: %3" ).arg( fid ).arg( idx ).arg( value.toString() ).arg( mFeatureRequest.filterType() ), 3 );
285 
286  if ( mSortCacheAttributes.contains( idx ) )
287  {
288  if ( mSortFieldIndex == -1 )
289  {
290  loadFeatureAtId( fid );
291  mExpressionContext.setFeature( mFeat );
292  mSortCache[fid] = mSortCacheExpression.evaluate( &mExpressionContext );
293  }
294  else
295  {
296  QgsFieldFormatter *fieldFormatter = mFieldFormatters.at( mSortFieldIndex );
297  const QVariant &widgetCache = mAttributeWidgetCaches.at( mSortFieldIndex );
298  const QVariantMap &widgetConfig = mWidgetConfigs.at( mSortFieldIndex );
299  QVariant sortValue = fieldFormatter->representValue( layer(), mSortFieldIndex, widgetConfig, widgetCache, value );
300  mSortCache.insert( fid, sortValue );
301  }
302  }
303  // No filter request: skip all possibly heavy checks
304  if ( mFeatureRequest.filterType() == QgsFeatureRequest::FilterNone )
305  {
306  setData( index( idToRow( fid ), fieldCol( idx ) ), value, Qt::EditRole );
307  }
308  else
309  {
310  if ( loadFeatureAtId( fid ) )
311  {
312  if ( mFeatureRequest.acceptFeature( mFeat ) )
313  {
314  if ( !mIdRowMap.contains( fid ) )
315  {
316  // Feature changed in such a way, it will be shown now
317  featureAdded( fid );
318  }
319  else
320  {
321  // Update representation
322  setData( index( idToRow( fid ), fieldCol( idx ) ), value, Qt::EditRole );
323  }
324  }
325  else
326  {
327  if ( mIdRowMap.contains( fid ) )
328  {
329  // Feature changed such, that it is no longer shown
330  featuresDeleted( QgsFeatureIds() << fid );
331  }
332  // else: we don't care
333  }
334  }
335  }
336 }
337 
338 void QgsAttributeTableModel::loadAttributes()
339 {
340  if ( !layer() )
341  {
342  return;
343  }
344 
345  bool ins = false, rm = false;
346 
347  QgsAttributeList attributes;
348  const QgsFields &fields = layer()->fields();
349 
350  mWidgetFactories.clear();
351  mAttributeWidgetCaches.clear();
352  mWidgetConfigs.clear();
353 
354  for ( int idx = 0; idx < fields.count(); ++idx )
355  {
356  const QgsEditorWidgetSetup setup = QgsGui::editorWidgetRegistry()->findBest( layer(), fields[idx].name() );
357  QgsEditorWidgetFactory *widgetFactory = QgsGui::editorWidgetRegistry()->factory( setup.type() );
359 
360  if ( widgetFactory )
361  {
362  mWidgetFactories.append( widgetFactory );
363  mWidgetConfigs.append( setup.config() );
364  mAttributeWidgetCaches.append( fieldFormatter->createCache( layer(), idx, setup.config() ) );
365  mFieldFormatters.append( fieldFormatter );
366 
367  attributes << idx;
368  }
369  }
370 
371  if ( mFieldCount + mExtraColumns < attributes.size() + mExtraColumns )
372  {
373  ins = true;
374  beginInsertColumns( QModelIndex(), mFieldCount + mExtraColumns, attributes.size() - 1 );
375  }
376  else if ( attributes.size() + mExtraColumns < mFieldCount + mExtraColumns )
377  {
378  rm = true;
379  beginRemoveColumns( QModelIndex(), attributes.size(), mFieldCount + mExtraColumns - 1 );
380  }
381 
382  mFieldCount = attributes.size();
383  mAttributes = attributes;
384 
385  if ( mSortFieldIndex >= mAttributes.count() )
386  mSortFieldIndex = -1;
387 
388  if ( ins )
389  {
390  endInsertColumns();
391  }
392  else if ( rm )
393  {
394  endRemoveColumns();
395  }
396 }
397 
399 {
400  // make sure attributes are properly updated before caching the data
401  // (emit of progress() signal may enter event loop and thus attribute
402  // table view may be updated with inconsistent model which may assume
403  // wrong number of attributes)
404  loadAttributes();
405 
406  beginResetModel();
407 
408  if ( rowCount() != 0 )
409  {
410  removeRows( 0, rowCount() );
411  }
412 
413  QgsFeatureIterator features = mLayerCache->getFeatures( mFeatureRequest );
414 
415  int i = 0;
416 
417  QTime t;
418  t.start();
419 
420  while ( features.nextFeature( mFeat ) )
421  {
422  ++i;
423 
424  if ( t.elapsed() > 1000 )
425  {
426  bool cancel = false;
427  emit progress( i, cancel );
428  if ( cancel )
429  break;
430 
431  t.restart();
432  }
433  featureAdded( mFeat.id(), true );
434  }
435 
436  emit finished();
437 
438  connect( mLayerCache, &QgsVectorLayerCache::invalidated, this, &QgsAttributeTableModel::loadLayer, Qt::UniqueConnection );
439  endResetModel();
440 }
441 
442 
444 {
445  if ( fieldName.isNull() )
446  {
447  mRowStylesMap.clear();
448  emit dataChanged( index( 0, 0 ), index( rowCount() - 1, columnCount() - 1 ) );
449  return;
450  }
451 
452  int fieldIndex = mLayerCache->layer()->fields().lookupField( fieldName );
453  if ( fieldIndex == -1 )
454  return;
455 
456  //whole column has changed
457  int col = fieldCol( fieldIndex );
458  emit dataChanged( index( 0, col ), index( rowCount() - 1, col ) );
459 }
460 
462 {
463  if ( a == b )
464  return;
465 
466  int rowA = idToRow( a );
467  int rowB = idToRow( b );
468 
469  //emit layoutAboutToBeChanged();
470 
471  mRowIdMap.remove( rowA );
472  mRowIdMap.remove( rowB );
473  mRowIdMap.insert( rowA, b );
474  mRowIdMap.insert( rowB, a );
475 
476  mIdRowMap.remove( a );
477  mIdRowMap.remove( b );
478  mIdRowMap.insert( a, rowB );
479  mIdRowMap.insert( b, rowA );
480  Q_ASSERT( mRowIdMap.size() == mIdRowMap.size() );
481 
482 
483  //emit layoutChanged();
484 }
485 
487 {
488  if ( !mIdRowMap.contains( id ) )
489  {
490  QgsDebugMsg( QString( "idToRow: id %1 not in the map" ).arg( id ) );
491  return -1;
492  }
493 
494  return mIdRowMap[id];
495 }
496 
498 {
499  return index( idToRow( id ), 0 );
500 }
501 
503 {
504  QModelIndexList indexes;
505 
506  int row = idToRow( id );
507  int columns = columnCount();
508  indexes.reserve( columns );
509  for ( int column = 0; column < columns; ++column )
510  {
511  indexes.append( index( row, column ) );
512  }
513 
514  return indexes;
515 }
516 
518 {
519  if ( !mRowIdMap.contains( row ) )
520  {
521  QgsDebugMsg( QString( "rowToId: row %1 not in the map" ).arg( row ) );
522  // return negative infinite (to avoid collision with newly added features)
524  }
525 
526  return mRowIdMap[row];
527 }
528 
530 {
531  return mAttributes[col];
532 }
533 
535 {
536  return mAttributes.indexOf( idx );
537 }
538 
539 int QgsAttributeTableModel::rowCount( const QModelIndex &parent ) const
540 {
541  Q_UNUSED( parent );
542  return mRowIdMap.size();
543 }
544 
545 int QgsAttributeTableModel::columnCount( const QModelIndex &parent ) const
546 {
547  Q_UNUSED( parent );
548  return qMax( 1, mFieldCount + mExtraColumns ); // if there are zero columns all model indices will be considered invalid
549 }
550 
551 QVariant QgsAttributeTableModel::headerData( int section, Qt::Orientation orientation, int role ) const
552 {
553  if ( !layer() )
554  return QVariant();
555 
556  if ( role == Qt::DisplayRole )
557  {
558  if ( orientation == Qt::Vertical ) //row
559  {
560  return QVariant( section );
561  }
562  else if ( section >= 0 && section < mFieldCount )
563  {
564  QString attributeName = layer()->fields().at( mAttributes.at( section ) ).displayName();
565  return QVariant( attributeName );
566  }
567  else
568  {
569  return tr( "extra column" );
570  }
571  }
572  else if ( role == Qt::ToolTipRole )
573  {
574  if ( orientation == Qt::Vertical )
575  {
576  // TODO show DisplayExpression
577  return tr( "Feature ID: %1" ).arg( rowToId( section ) );
578  }
579  else
580  {
581  QgsField field = layer()->fields().at( mAttributes.at( section ) );
582  return field.name();
583  }
584  }
585  else
586  {
587  return QVariant();
588  }
589 }
590 
591 QVariant QgsAttributeTableModel::data( const QModelIndex &index, int role ) const
592 {
593  if ( !index.isValid() ||
594  ( role != Qt::TextAlignmentRole
595  && role != Qt::DisplayRole
596  && role != Qt::EditRole
597  && role != SortRole
598  && role != FeatureIdRole
599  && role != FieldIndexRole
600  && role != Qt::BackgroundColorRole
601  && role != Qt::TextColorRole
602  && role != Qt::DecorationRole
603  && role != Qt::FontRole
604  )
605  )
606  return QVariant();
607 
608  QgsFeatureId rowId = rowToId( index.row() );
609 
610  if ( role == FeatureIdRole )
611  return rowId;
612 
613  if ( index.column() >= mFieldCount )
614  return QVariant();
615 
616  int fieldId = mAttributes.at( index.column() );
617 
618  if ( role == FieldIndexRole )
619  return fieldId;
620 
621  if ( role == SortRole )
622  {
623  return mSortCache[rowId];
624  }
625 
626  QgsField field = layer()->fields().at( fieldId );
627 
628  if ( role == Qt::TextAlignmentRole )
629  {
630  return QVariant( mFieldFormatters.at( index.column() )->alignmentFlag( layer(), fieldId, mWidgetConfigs.at( index.column() ) ) | Qt::AlignVCenter );
631  }
632 
633  if ( mFeat.id() != rowId || !mFeat.isValid() )
634  {
635  if ( !loadFeatureAtId( rowId ) )
636  return QVariant( "ERROR" );
637 
638  if ( mFeat.id() != rowId )
639  return QVariant( "ERROR" );
640  }
641 
642  QVariant val = mFeat.attribute( fieldId );
643 
644  switch ( role )
645  {
646  case Qt::DisplayRole:
647  return mFieldFormatters.at( index.column() )->representValue( layer(), fieldId, mWidgetConfigs.at( index.column() ),
648  mAttributeWidgetCaches.at( index.column() ), val );
649 
650  case Qt::EditRole:
651  return val;
652 
653  case Qt::BackgroundColorRole:
654  case Qt::TextColorRole:
655  case Qt::DecorationRole:
656  case Qt::FontRole:
657  {
658  mExpressionContext.setFeature( mFeat );
659  QList<QgsConditionalStyle> styles;
660  if ( mRowStylesMap.contains( index.row() ) )
661  {
662  styles = mRowStylesMap[index.row()];
663  }
664  else
665  {
666  styles = QgsConditionalStyle::matchingConditionalStyles( layer()->conditionalStyles()->rowStyles(), QVariant(), mExpressionContext );
667  mRowStylesMap.insert( index.row(), styles );
668  }
669 
671  styles = layer()->conditionalStyles()->fieldStyles( field.name() );
672  styles = QgsConditionalStyle::matchingConditionalStyles( styles, val, mExpressionContext );
673  styles.insert( 0, rowstyle );
675 
676  if ( style.isValid() )
677  {
678  if ( role == Qt::BackgroundColorRole && style.validBackgroundColor() )
679  return style.backgroundColor();
680  if ( role == Qt::TextColorRole && style.validTextColor() )
681  return style.textColor();
682  if ( role == Qt::DecorationRole )
683  return style.icon();
684  if ( role == Qt::FontRole )
685  return style.font();
686  }
687 
688  return QVariant();
689  }
690  }
691 
692  return QVariant();
693 }
694 
695 bool QgsAttributeTableModel::setData( const QModelIndex &index, const QVariant &value, int role )
696 {
697  Q_UNUSED( value )
698 
699  if ( !index.isValid() || index.column() >= mFieldCount || role != Qt::EditRole || !layer()->isEditable() )
700  return false;
701 
702  if ( !layer()->isModified() )
703  return false;
704 
705  if ( mChangedCellBounds.isNull() )
706  {
707  mChangedCellBounds = QRect( index.column(), index.row(), 1, 1 );
708  }
709  else
710  {
711  if ( index.column() < mChangedCellBounds.left() )
712  {
713  mChangedCellBounds.setLeft( index.column() );
714  }
715  if ( index.row() < mChangedCellBounds.top() )
716  {
717  mChangedCellBounds.setTop( index.row() );
718  }
719  if ( index.column() > mChangedCellBounds.right() )
720  {
721  mChangedCellBounds.setRight( index.column() );
722  }
723  if ( index.row() > mChangedCellBounds.bottom() )
724  {
725  mChangedCellBounds.setBottom( index.row() );
726  }
727  }
728 
729  return true;
730 }
731 
732 Qt::ItemFlags QgsAttributeTableModel::flags( const QModelIndex &index ) const
733 {
734  if ( !index.isValid() )
735  return Qt::ItemIsEnabled;
736 
737  if ( index.column() >= mFieldCount )
738  return Qt::NoItemFlags;
739 
740  Qt::ItemFlags flags = QAbstractItemModel::flags( index );
741 
742  if ( layer()->isEditable() &&
743  !layer()->editFormConfig().readOnly( mAttributes[index.column()] ) &&
744  ( ( layer()->dataProvider() && layer()->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues ) ||
745  FID_IS_NEW( rowToId( index.row() ) ) ) )
746  flags |= Qt::ItemIsEditable;
747 
748  return flags;
749 }
750 
751 void QgsAttributeTableModel::reload( const QModelIndex &index1, const QModelIndex &index2 )
752 {
754  emit dataChanged( index1, index2 );
755 }
756 
757 
758 void QgsAttributeTableModel::executeAction( const QUuid &action, const QModelIndex &idx ) const
759 {
760  QgsFeature f = feature( idx );
761  layer()->actions()->doAction( action, f, fieldIdx( idx.column() ) );
762 }
763 
764 void QgsAttributeTableModel::executeMapLayerAction( QgsMapLayerAction *action, const QModelIndex &idx ) const
765 {
766  QgsFeature f = feature( idx );
767  action->triggerForFeature( layer(), &f );
768 }
769 
770 QgsFeature QgsAttributeTableModel::feature( const QModelIndex &idx ) const
771 {
772  QgsFeature f;
773  f.initAttributes( mAttributes.size() );
774  f.setId( rowToId( idx.row() ) );
775  for ( int i = 0; i < mAttributes.size(); i++ )
776  {
777  f.setAttribute( mAttributes[i], data( index( idx.row(), i ), Qt::EditRole ) );
778  }
779 
780  return f;
781 }
782 
784 {
785  if ( column == -1 || column >= mAttributes.count() )
786  {
787  prefetchSortData( QString() );
788  }
789  else
790  {
791  prefetchSortData( QgsExpression::quotedColumnRef( mLayerCache->layer()->fields().at( mAttributes.at( column ) ).name() ) );
792  }
793 }
794 
795 void QgsAttributeTableModel::prefetchSortData( const QString &expressionString )
796 {
797  mSortCache.clear();
798  mSortCacheAttributes.clear();
799  mSortFieldIndex = -1;
800  if ( !expressionString.isEmpty() )
801  mSortCacheExpression = QgsExpression( expressionString );
802  else
803  {
804  // no sorting
805  mSortCacheExpression = QgsExpression();
806  return;
807  }
808 
809  QgsFieldFormatter *fieldFormatter = nullptr;
810  QVariant widgetCache;
811  QVariantMap widgetConfig;
812 
813  if ( mSortCacheExpression.isField() )
814  {
815  QString fieldName = static_cast<const QgsExpressionNodeColumnRef *>( mSortCacheExpression.rootNode() )->name();
816  mSortFieldIndex = mLayerCache->layer()->fields().lookupField( fieldName );
817  }
818 
819  if ( mSortFieldIndex == -1 )
820  {
821  mSortCacheExpression.prepare( &mExpressionContext );
822 
823  Q_FOREACH ( const QString &col, mSortCacheExpression.referencedColumns() )
824  {
825  mSortCacheAttributes.append( mLayerCache->layer()->fields().lookupField( col ) );
826  }
827  }
828  else
829  {
830  mSortCacheAttributes.append( mSortFieldIndex );
831 
832  widgetCache = mAttributeWidgetCaches.at( mSortFieldIndex );
833  widgetConfig = mWidgetConfigs.at( mSortFieldIndex );
834  fieldFormatter = mFieldFormatters.at( mSortFieldIndex );
835  }
836 
837  QgsFeatureRequest request = QgsFeatureRequest( mFeatureRequest )
839  .setSubsetOfAttributes( mSortCacheAttributes );
840  QgsFeatureIterator it = mLayerCache->getFeatures( request );
841 
842  QgsFeature f;
843  while ( it.nextFeature( f ) )
844  {
845  if ( mSortFieldIndex == -1 )
846  {
847  mExpressionContext.setFeature( f );
848  mSortCache.insert( f.id(), mSortCacheExpression.evaluate( &mExpressionContext ) );
849  }
850  else
851  {
852  QVariant sortValue = fieldFormatter->sortValue( layer(), mSortFieldIndex, widgetConfig, widgetCache, f.attribute( mSortFieldIndex ) );
853  mSortCache.insert( f.id(), sortValue );
854  }
855  }
856 }
857 
859 {
860  if ( mSortCacheExpression.isValid() )
861  return mSortCacheExpression.expression();
862  else
863  return QString();
864 }
865 
867 {
868  mFeatureRequest = request;
869  if ( layer() && !layer()->hasGeometryType() )
870  mFeatureRequest.setFlags( mFeatureRequest.flags() | QgsFeatureRequest::NoGeometry );
871 }
872 
874 {
875  return mFeatureRequest;
876 }
int lookupField(const QString &fieldName) const
Look up field&#39;s index from the field name.
Definition: qgsfields.cpp:289
bool isValid() const
Returns the validity of this feature.
Definition: qgsfeature.cpp:176
void setRequest(const QgsFeatureRequest &request)
Set a request that will be used to fill this attribute table model.
QgsActionManager * actions()
Get all layer actions defined on this layer.
QgsFeatureId id
Definition: qgsfeature.h:70
Wrapper for iterator of features from vector data provider or vector layer.
void featuresDeleted(const QgsFeatureIds &fids)
Emitted when features have been deleted.
QgsVectorLayer * layer() const
Returns the layer this model uses as backend.
int extraColumns() const
Empty extra columns to announce from this model.
bool acceptFeature(const QgsFeature &feature)
Check if a feature is accepted by this requests filter.
virtual void loadLayer()
Loads the layer into the model Preferably to be called, before using this model as source for any oth...
QVariantMap config() const
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Get the registry of available field formatters.
const Flags & flags() const
QString name
Definition: qgsfield.h:54
Get the field index of this column.
void invalidated()
The cache has been invalidated and cleared.
QgsEditorWidgetFactory * factory(const QString &widgetId)
Get a factory for the given widget type id.
virtual QVariant createCache(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config) const
Create a cache for a given field.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
#define QgsDebugMsg(str)
Definition: qgslogger.h:37
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeature.h:519
QList< QgsConditionalStyle > fieldStyles(const QString &fieldName)
Returns the conditional styles set for the field UI properties.
void reload(const QModelIndex &index1, const QModelIndex &index2)
Reloads the model data between indices.
#define FID_TO_STRING(fid)
Definition: qgsfeature.h:52
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
FilterType filterType() const
Return the filter type which is currently set on this request.
virtual QVariant sortValue(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value) const
If the default sort order should be overwritten for this widget, you can transform the value in here...
QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
Container of fields for a vector layer.
Definition: qgsfields.h:41
bool setAttribute(int field, const QVariant &attr)
Set an attribute&#39;s value by field index.
Definition: qgsfeature.cpp:204
bool validBackgroundColor() const
Check if the background color is valid for render.
QPixmap icon() const
The icon set for style generated from the set symbol.
void fieldConditionalStyleChanged(const QString &fieldName)
Handles updating the model when the conditional style for a field changes.
QgsVectorLayer * layer()
Returns the layer to which this cache belongs.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:61
void executeAction(const QUuid &action, const QModelIndex &idx) const
Execute an action.
void doAction(const QUuid &actionId, const QgsFeature &feature, int defaultValueIndex=0)
Does the given action.
void attributeValueChanged(QgsFeatureId fid, int field, const QVariant &value)
Is emitted when an attribute is changed.
virtual bool isEditable() const override
Returns true if the provider is in editing mode.
int count() const
Return number of items.
Definition: qgsfields.cpp:115
void editCommandEnded()
Signal emitted, when an edit command successfully ended.
void resetModel()
Resets the model.
QModelIndex idToIndex(QgsFeatureId id) const
QgsFields fields() const
Returns the list of fields of this layer.
QgsConditionalLayerStyles * conditionalStyles() const
Return the conditional styles that are set for this layer.
QgsField at(int i) const
Get field at particular index (must be in range 0..N-1)
Definition: qgsfields.cpp:135
virtual QVariant data(const QModelIndex &index, int role) const override
Returns data on the given index.
Get the feature id of the feature in this row.
QgsFeature feature(const QModelIndex &idx) const
Return the feature attributes at given model index.
void featureAdded(QgsFeatureId fid)
Is emitted, when a new feature has been added to the layer and this cache.
QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const override
Returns header data.
Conditional styling for a rule.
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:38
void setExtraColumns(int extraColumns)
Empty extra columns to announce from this model.
int columnCount(const QModelIndex &parent=QModelIndex()) const override
Returns the number of columns.
static QgsEditorWidgetRegistry * editorWidgetRegistry()
Returns the global editor widget registry, used for managing all known edit widget factories...
Definition: qgsgui.cpp:40
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
Definition: qgsfeature.cpp:195
bool isValid() const
isValid Check if this rule is valid.
static QList< QgsConditionalStyle > matchingConditionalStyles(const QList< QgsConditionalStyle > &styles, const QVariant &value, QgsExpressionContext &context)
Find and return the matching styles for the value and feature.
Every attribute editor widget needs a factory, which inherits this class.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
QColor backgroundColor() const
The background color for style.
bool removeRows(int row, int count, const QModelIndex &parent=QModelIndex()) override
Remove rows.
static QgsConditionalStyle compressStyles(const QList< QgsConditionalStyle > &styles)
Compress a list of styles into a single style.
const QgsFeatureRequest & request() const
Get the the feature request.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer&#39;s project and layer.
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:46
double ANALYSIS_EXPORT min(double x, double y)
Returns the minimum of two doubles or the first argument if both are equal.
Definition: MathUtils.cc:452
void setId(QgsFeatureId id)
Sets the feature ID for this feature.
Definition: qgsfeature.cpp:112
void cachedLayerDeleted()
Is emitted when the cached layer is deleted.
QgsFieldFormatter * fieldFormatter(const QString &id) const
Get a field formatter by its id.
A field formatter helps to handle and display values for a field.
QModelIndexList idToIndexList(QgsFeatureId id) const
This class caches features of a given QgsVectorLayer.
static int debugLevel()
Reads the environment variable QGIS_DEBUG and converts it to int.
Definition: qgslogger.h:97
void progress(int i, bool &cancel)
void modelChanged()
Model has been changed.
QColor textColor() const
The text color set for style.
QgsAttributeTableModel(QgsVectorLayerCache *layerCache, QObject *parent=nullptr)
Constructor.
int fieldCol(int idx) const
get column from field index
No filter is applied.
int fieldIdx(int col) const
get field index from column
virtual QString representValue(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value) const
Create a pretty String representation of the value.
QgsEditorWidgetSetup findBest(const QgsVectorLayer *vl, const QString &fieldName) const
Find the best editor widget and its configuration for a given field.
virtual int rowCount(const QModelIndex &parent=QModelIndex()) const override
Returns the number of rows.
Holder for the widget type and its configuration for a field.
bool featureAtId(QgsFeatureId featureId, QgsFeature &feature, bool skipCache=false)
Gets the feature at the given feature id.
bool validTextColor() const
Check if the text color is valid for render.
virtual bool isModified() const
Returns true if the provider has been modified since the last commit.
void executeMapLayerAction(QgsMapLayerAction *action, const QModelIndex &idx) const
Execute a QgsMapLayerAction.
QgsFieldFormatter * fallbackFieldFormatter() const
Returns a basic fallback field formatter which can be used to represent any field in an unspectacular...
QgsFeatureId rowToId(int row) const
Maps row to feature id.
qint64 QgsFeatureId
Definition: qgsfeature.h:37
QString sortCacheExpression() const
The expression which was used to fill the sorting cache.
#define FID_IS_NEW(fid)
Definition: qgsfeature.h:50
void appendScopes(const QList< QgsExpressionContextScope *> &scopes)
Appends a list of scopes to the end of the context.
QList< int > QgsAttributeList
Definition: qgsfield.h:27
QFont font() const
The font for the style.
void swapRows(QgsFeatureId a, QgsFeatureId b)
Swaps two rows.
bool nextFeature(QgsFeature &f)
void attributeDeleted(int idx)
Will be emitted, when an attribute has been deleted from this vector layer.
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
Definition: qgsfeature.cpp:255
QgsFeatureIterator getFeatures(const QgsFeatureRequest &featureRequest=QgsFeatureRequest())
Query this VectorLayerCache for features.
void updatedFields()
Is emitted, whenever the fields available from this layer have been changed.
int idToRow(QgsFeatureId id) const
Maps feature id to table row.
virtual bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole) override
Updates data on given index.
void triggerForFeature(QgsMapLayer *layer, const QgsFeature *feature)
Triggers the action with the specified layer and feature.
Allows modification of attribute values.
An action which can run on map layers.
void prefetchColumnData(int column)
Caches the entire data for one column.
void prefetchSortData(const QString &expression)
Prefetches the entire data for one expression.
Qt::ItemFlags flags(const QModelIndex &index) const override
Returns item flags for the index.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Set flags that affect how features will be fetched.