QGIS API Documentation  2.99.0-Master (d55fa22)
qgsattributetableview.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  QgsAttributeTableView.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 <QKeyEvent>
17 #include <QHeaderView>
18 #include <QMenu>
19 #include <QToolButton>
20 #include <QHBoxLayout>
21 
22 #include "qgssettings.h"
23 #include "qgsactionmanager.h"
24 #include "qgsattributetableview.h"
25 #include "qgsattributetablemodel.h"
28 #include "qgsvectorlayer.h"
29 #include "qgsvectorlayercache.h"
31 #include "qgsvectordataprovider.h"
32 #include "qgslogger.h"
33 #include "qgsmapcanvas.h"
36 #include "qgsfeatureiterator.h"
37 #include "qgsgui.h"
38 
40  : QTableView( parent )
41  , mFilterModel( nullptr )
42  , mFeatureSelectionModel( nullptr )
43  , mFeatureSelectionManager( nullptr )
44  , mActionPopup( nullptr )
45  , mRowSectionAnchor( 0 )
46  , mCtrlDragSelectionFlag( QItemSelectionModel::Select )
47 {
48  QgsSettings settings;
49  restoreGeometry( settings.value( QStringLiteral( "BetterAttributeTable/geometry" ) ).toByteArray() );
50 
51  //verticalHeader()->setDefaultSectionSize( 20 );
52  horizontalHeader()->setHighlightSections( false );
53 
54  // We need mouse move events to create the action button on hover
55  mTableDelegate = new QgsAttributeTableDelegate( this );
56  setItemDelegate( mTableDelegate );
57 
58  setEditTriggers( QAbstractItemView::AllEditTriggers );
59 
60  setSelectionBehavior( QAbstractItemView::SelectRows );
61  setSelectionMode( QAbstractItemView::ExtendedSelection );
62  setSortingEnabled( true ); // At this point no data is in the model yet, so actually nothing is sorted.
63  horizontalHeader()->setSortIndicatorShown( false ); // So hide the indicator to avoid confusion.
64 
65  verticalHeader()->viewport()->installEventFilter( this );
66 
67  connect( verticalHeader(), &QHeaderView::sectionPressed, this, [ = ]( int row ) { selectRow( row, true ); } );
68  connect( verticalHeader(), &QHeaderView::sectionEntered, this, &QgsAttributeTableView::_q_selectRow );
69  connect( horizontalHeader(), &QHeaderView::sectionResized, this, &QgsAttributeTableView::columnSizeChanged );
70  connect( horizontalHeader(), &QHeaderView::sortIndicatorChanged, this, &QgsAttributeTableView::showHorizontalSortIndicator );
71  connect( QgsGui::mapLayerActionRegistry(), &QgsMapLayerActionRegistry::changed, this, &QgsAttributeTableView::recreateActionWidgets );
72 }
73 
74 bool QgsAttributeTableView::eventFilter( QObject *object, QEvent *event )
75 {
76  if ( object == verticalHeader()->viewport() )
77  {
78  switch ( event->type() )
79  {
80  case QEvent::MouseButtonPress:
81  mFeatureSelectionModel->enableSync( false );
82  break;
83 
84  case QEvent::MouseButtonRelease:
85  mFeatureSelectionModel->enableSync( true );
86  break;
87 
88  default:
89  break;
90  }
91  }
92  return false;
93 }
94 
96 {
97  int i = 0;
98  Q_FOREACH ( const QgsAttributeTableConfig::ColumnConfig &columnConfig, config.columns() )
99  {
100  if ( columnConfig.hidden )
101  continue;
102 
103  if ( columnConfig.width >= 0 )
104  {
105  setColumnWidth( i, columnConfig.width );
106  }
107  else
108  {
109  setColumnWidth( i, horizontalHeader()->defaultSectionSize() );
110  }
111  i++;
112  }
113 }
114 
116 {
117  mFilterModel = filterModel;
118  QTableView::setModel( filterModel );
119 
120  if ( mFilterModel )
121  {
122  connect( mFilterModel, &QObject::destroyed, this, &QgsAttributeTableView::modelDeleted );
123  connect( mTableDelegate, &QgsAttributeTableDelegate::actionColumnItemPainted, this, &QgsAttributeTableView::onActionColumnItemPainted );
124  }
125 
126  delete mFeatureSelectionModel;
127  mFeatureSelectionModel = nullptr;
128 
129  if ( filterModel )
130  {
131  if ( !mFeatureSelectionManager )
132  {
133  mFeatureSelectionManager = new QgsVectorLayerSelectionManager( mFilterModel->layer(), mFilterModel );
134  }
135 
136  mFeatureSelectionModel = new QgsFeatureSelectionModel( mFilterModel, mFilterModel, mFeatureSelectionManager, mFilterModel );
137  setSelectionModel( mFeatureSelectionModel );
138  mTableDelegate->setFeatureSelectionModel( mFeatureSelectionModel );
139  connect( mFeatureSelectionModel, static_cast<void ( QgsFeatureSelectionModel::* )( const QModelIndexList &indexes )>( &QgsFeatureSelectionModel::requestRepaint ),
140  this, static_cast<void ( QgsAttributeTableView::* )( const QModelIndexList &indexes )>( &QgsAttributeTableView::repaintRequested ) );
141  connect( mFeatureSelectionModel, static_cast<void ( QgsFeatureSelectionModel::* )()>( &QgsFeatureSelectionModel::requestRepaint ),
142  this, static_cast<void ( QgsAttributeTableView::* )()>( &QgsAttributeTableView::repaintRequested ) );
143  }
144 }
145 
147 {
148  if ( mFeatureSelectionManager )
149  delete mFeatureSelectionManager;
150 
151  mFeatureSelectionManager = featureSelectionManager;
152 
153  if ( mFeatureSelectionModel )
154  mFeatureSelectionModel->setFeatureSelectionManager( mFeatureSelectionManager );
155 }
156 
157 QWidget *QgsAttributeTableView::createActionWidget( QgsFeatureId fid )
158 {
159  QgsAttributeTableConfig attributeTableConfig = mFilterModel->layer()->attributeTableConfig();
160 
161  QToolButton *toolButton = nullptr;
162  QWidget *container = nullptr;
163 
164  if ( attributeTableConfig.actionWidgetStyle() == QgsAttributeTableConfig::DropDown )
165  {
166  toolButton = new QToolButton();
167  toolButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
168  toolButton->setPopupMode( QToolButton::MenuButtonPopup );
169  container = toolButton;
170  }
171  else
172  {
173  container = new QWidget();
174  container->setLayout( new QHBoxLayout() );
175  container->layout()->setMargin( 0 );
176  }
177 
178  QList< QAction * > actionList;
179  QAction *defaultAction = nullptr;
180 
181  // first add user created layer actions
182  QList<QgsAction> actions = mFilterModel->layer()->actions()->actions( QStringLiteral( "Feature" ) );
183  Q_FOREACH ( const QgsAction &action, actions )
184  {
185  QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : QLatin1String( "" );
186  QAction *act = new QAction( action.icon(), actionTitle, container );
187  act->setToolTip( action.name() );
188  act->setData( "user_action" );
189  act->setProperty( "fid", fid );
190  act->setProperty( "action_id", action.id() );
191  connect( act, &QAction::triggered, this, &QgsAttributeTableView::actionTriggered );
192  actionList << act;
193 
194  if ( mFilterModel->layer()->actions()->defaultAction( QStringLiteral( "AttributeTableRow" ) ).id() == action.id() )
195  defaultAction = act;
196  }
197 
198  // next add any registered actions for this layer
199  Q_FOREACH ( QgsMapLayerAction *mapLayerAction,
200  QgsGui::mapLayerActionRegistry()->mapLayerActions( mFilterModel->layer(),
202  {
203  QAction *action = new QAction( mapLayerAction->icon(), mapLayerAction->text(), container );
204  action->setData( "map_layer_action" );
205  action->setToolTip( mapLayerAction->text() );
206  action->setProperty( "fid", fid );
207  action->setProperty( "action", qVariantFromValue( qobject_cast<QObject *>( mapLayerAction ) ) );
208  connect( action, &QAction::triggered, this, &QgsAttributeTableView::actionTriggered );
209  actionList << action;
210 
211  if ( !defaultAction &&
212  QgsGui::mapLayerActionRegistry()->defaultActionForLayer( mFilterModel->layer() ) == mapLayerAction )
213  defaultAction = action;
214  }
215 
216  if ( !defaultAction && !actionList.isEmpty() )
217  defaultAction = actionList.at( 0 );
218 
219  Q_FOREACH ( QAction *act, actionList )
220  {
221  if ( attributeTableConfig.actionWidgetStyle() == QgsAttributeTableConfig::DropDown )
222  {
223  toolButton->addAction( act );
224 
225  if ( act == defaultAction )
226  toolButton->setDefaultAction( act );
227 
228  container = toolButton;
229  }
230  else
231  {
232  QToolButton *btn = new QToolButton;
233  btn->setDefaultAction( act );
234  container->layout()->addWidget( btn );
235  }
236  }
237 
238  if ( attributeTableConfig.actionWidgetStyle() == QgsAttributeTableConfig::ButtonList )
239  {
240  static_cast< QHBoxLayout * >( container->layout() )->addStretch();
241  }
242 
243  // TODO: Rethink default actions
244 #if 0
245  if ( toolButton && !toolButton->actions().isEmpty() && actions->defaultAction() == -1 )
246  toolButton->setDefaultAction( toolButton->actions().at( 0 ) );
247 #endif
248 
249  return container;
250 }
251 
252 void QgsAttributeTableView::closeEvent( QCloseEvent *e )
253 {
254  Q_UNUSED( e );
255  QgsSettings settings;
256  settings.setValue( QStringLiteral( "BetterAttributeTable/geometry" ), QVariant( saveGeometry() ) );
257 }
258 
259 void QgsAttributeTableView::mousePressEvent( QMouseEvent *event )
260 {
261  setSelectionMode( QAbstractItemView::NoSelection );
262  QTableView::mousePressEvent( event );
263  setSelectionMode( QAbstractItemView::ExtendedSelection );
264 }
265 
267 {
268  setSelectionMode( QAbstractItemView::NoSelection );
269  QTableView::mouseReleaseEvent( event );
270  setSelectionMode( QAbstractItemView::ExtendedSelection );
271 }
272 
273 void QgsAttributeTableView::mouseMoveEvent( QMouseEvent *event )
274 {
275  setSelectionMode( QAbstractItemView::NoSelection );
276  QTableView::mouseMoveEvent( event );
277  setSelectionMode( QAbstractItemView::ExtendedSelection );
278 }
279 
280 void QgsAttributeTableView::keyPressEvent( QKeyEvent *event )
281 {
282  switch ( event->key() )
283  {
284 
285  // Default Qt behavior would be to change the selection.
286  // We don't make it that easy for the user to trash his selection.
287  case Qt::Key_Up:
288  case Qt::Key_Down:
289  case Qt::Key_Left:
290  case Qt::Key_Right:
291  setSelectionMode( QAbstractItemView::NoSelection );
292  QTableView::keyPressEvent( event );
293  setSelectionMode( QAbstractItemView::ExtendedSelection );
294  break;
295 
296  default:
297  QTableView::keyPressEvent( event );
298  break;
299  }
300 }
301 
302 void QgsAttributeTableView::repaintRequested( const QModelIndexList &indexes )
303 {
304  Q_FOREACH ( const QModelIndex &index, indexes )
305  {
306  update( index );
307  }
308 }
309 
311 {
312  setDirtyRegion( viewport()->rect() );
313 }
314 
316 {
317  QItemSelection selection;
318  selection.append( QItemSelectionRange( mFilterModel->index( 0, 0 ), mFilterModel->index( mFilterModel->rowCount() - 1, 0 ) ) );
319  mFeatureSelectionModel->selectFeatures( selection, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
320 }
321 
322 void QgsAttributeTableView::contextMenuEvent( QContextMenuEvent *event )
323 {
324  delete mActionPopup;
325  mActionPopup = nullptr;
326 
327  QModelIndex idx = indexAt( event->pos() );
328  if ( !idx.isValid() )
329  {
330  return;
331  }
332 
333  QgsVectorLayer *vlayer = mFilterModel->layer();
334  if ( !vlayer )
335  return;
336 
337  mActionPopup = new QMenu( this );
338 
339  mActionPopup->addAction( tr( "Select All" ), this, SLOT( selectAll() ), QKeySequence::SelectAll );
340 
341  // let some other parts of the application add some actions
342  emit willShowContextMenu( mActionPopup, idx );
343 
344  if ( !mActionPopup->actions().isEmpty() )
345  {
346  mActionPopup->popup( event->globalPos() );
347  }
348 }
349 
351 {
352  selectRow( row, true );
353 }
354 
356 {
357  selectRow( row, false );
358 }
359 
360 void QgsAttributeTableView::modelDeleted()
361 {
362  mFilterModel = nullptr;
363  mFeatureSelectionManager = nullptr;
364  mFeatureSelectionModel = nullptr;
365 }
366 
367 void QgsAttributeTableView::selectRow( int row, bool anchor )
368 {
369  if ( selectionBehavior() == QTableView::SelectColumns
370  || ( selectionMode() == QTableView::SingleSelection
371  && selectionBehavior() == QTableView::SelectItems ) )
372  return;
373 
374  if ( row >= 0 && row < model()->rowCount() )
375  {
376  int column = horizontalHeader()->logicalIndexAt( isRightToLeft() ? viewport()->width() : 0 );
377  QModelIndex index = model()->index( row, column );
378  QItemSelectionModel::SelectionFlags command = selectionCommand( index );
379  selectionModel()->setCurrentIndex( index, QItemSelectionModel::NoUpdate );
380  if ( ( anchor && !( command & QItemSelectionModel::Current ) )
381  || ( selectionMode() == QTableView::SingleSelection ) )
382  mRowSectionAnchor = row;
383 
384  if ( selectionMode() != QTableView::SingleSelection
385  && command.testFlag( QItemSelectionModel::Toggle ) )
386  {
387  if ( anchor )
388  mCtrlDragSelectionFlag = mFeatureSelectionModel->isSelected( index )
389  ? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
390  command &= ~QItemSelectionModel::Toggle;
391  command |= mCtrlDragSelectionFlag;
392  if ( !anchor )
393  command |= QItemSelectionModel::Current;
394  }
395 
396  QModelIndex tl = model()->index( qMin( mRowSectionAnchor, row ), 0 );
397  QModelIndex br = model()->index( qMax( mRowSectionAnchor, row ), model()->columnCount() - 1 );
398  if ( verticalHeader()->sectionsMoved() && tl.row() != br.row() )
399  setSelection( visualRect( tl ) | visualRect( br ), command );
400  else
401  mFeatureSelectionModel->selectFeatures( QItemSelection( tl, br ), command );
402  }
403 }
404 
405 void QgsAttributeTableView::showHorizontalSortIndicator()
406 {
407  horizontalHeader()->setSortIndicatorShown( true );
408 }
409 
410 void QgsAttributeTableView::actionTriggered()
411 {
412  QAction *action = qobject_cast<QAction *>( sender() );
413  QgsFeatureId fid = action->property( "fid" ).toLongLong();
414 
415  QgsFeature f;
416  mFilterModel->layerCache()->getFeatures( QgsFeatureRequest( fid ) ).nextFeature( f );
417 
418  if ( action->data().toString() == QLatin1String( "user_action" ) )
419  {
420  mFilterModel->layer()->actions()->doAction( action->property( "action_id" ).toString(), f );
421  }
422  else if ( action->data().toString() == QLatin1String( "map_layer_action" ) )
423  {
424  QObject *object = action->property( "action" ).value<QObject *>();
425  QgsMapLayerAction *layerAction = qobject_cast<QgsMapLayerAction *>( object );
426  if ( layerAction )
427  {
428  layerAction->triggerForFeature( mFilterModel->layer(), &f );
429  }
430  }
431 }
432 
433 void QgsAttributeTableView::columnSizeChanged( int index, int oldWidth, int newWidth )
434 {
435  Q_UNUSED( oldWidth )
436  emit columnResized( index, newWidth );
437 }
438 
439 void QgsAttributeTableView::onActionColumnItemPainted( const QModelIndex &index )
440 {
441  if ( !indexWidget( index ) )
442  {
443  QWidget *widget = createActionWidget( mFilterModel->data( index, QgsAttributeTableModel::FeatureIdRole ).toLongLong() );
444  mActionWidgets.insert( index, widget );
445  setIndexWidget( index, widget );
446  }
447 }
448 
449 void QgsAttributeTableView::recreateActionWidgets()
450 {
451  QMap< QModelIndex, QWidget * > newWidgets;
452  QMap< QModelIndex, QWidget * >::const_iterator it = mActionWidgets.constBegin();
453  for ( ; it != mActionWidgets.constEnd(); ++it )
454  {
455  it.value()->deleteLater(); //?
456  QWidget *widget = createActionWidget( mFilterModel->data( it.key(), QgsAttributeTableModel::FeatureIdRole ).toLongLong() );
457  newWidgets.insert( it.key(), widget );
458  setIndexWidget( it.key(), widget );
459  }
460  mActionWidgets = newWidgets;
461 }
QgsActionManager * actions()
Get all layer actions defined on this layer.
QgsVectorLayer * layer() const
Returns the layer this filter acts on.
virtual QVariant data(const QModelIndex &index, int role) const override
Provides a table view of features of a QgsVectorLayer.
virtual bool isSelected(QgsFeatureId fid)
Returns the selection status of a given feature id.
void willShowContextMenu(QMenu *menu, const QModelIndex &atIndex)
Is emitted, in order to provide a hook to add additional* menu entries to the context menu...
This class is a composition of two QSettings instances:
Definition: qgssettings.h:54
QList< QgsAction > actions(const QString &actionScope=QString()) const
Return a list of actions that are available in the given action scope.
void columnResized(int column, int width)
Emitted when a column in the view has been resized.
virtual bool eventFilter(QObject *object, QEvent *event) override
This event filter is installed on the verticalHeader to intercept mouse press and release events...
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:61
QString shortTitle() const
The short title is used to label user interface elements like buttons.
Definition: qgsaction.h:96
void doAction(const QUuid &actionId, const QgsFeature &feature, int defaultValueIndex=0)
Does the given action.
virtual void selectAll() override
void actionColumnItemPainted(const QModelIndex &index) const
Is emitted when an action column item is painted.
void enableSync(bool enable)
Enables or disables synchronisation to the QgsVectorLayer When synchronisation is disabled...
void setFeatureSelectionModel(QgsFeatureSelectionModel *featureSelectionModel)
void mouseReleaseEvent(QMouseEvent *event) override
Called for mouse release events on a table cell.
Get the feature id of the feature in this row.
void setValue(const QString &key, const QVariant &value, const QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
ActionWidgetStyle actionWidgetStyle() const
Get the style of the action widget.
void requestRepaint()
Request a repaint of the visible items of connected views.
QgsAttributeTableView(QWidget *parent=0)
Utility class that encapsulates an action based on vector attributes.
Definition: qgsaction.h:34
virtual void selectFeatures(const QItemSelection &selection, SelectionFlags command)
Select features on this table.
void mousePressEvent(QMouseEvent *event) override
Called for mouse press events on a table cell.
bool hidden
Flag that controls if the column is hidden.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
virtual void setFeatureSelectionManager(QgsIFeatureSelectionManager *featureSelectionManager)
QIcon icon() const
The icon.
Definition: qgsaction.h:116
QString name() const
The name of the action. This may be a longer description.
Definition: qgsaction.h:93
void changed()
Triggered when an action is added or removed from the registry.
QgsAction defaultAction(const QString &actionScope)
Each scope can have a default action.
virtual void setModel(QgsAttributeTableFilterModel *filterModel)
void mouseMoveEvent(QMouseEvent *event) override
Called for mouse move events on a table cell.
QVector< QgsAttributeTableConfig::ColumnConfig > columns() const
Get the list with all columns and their configuration.
QgsAttributeTableConfig attributeTableConfig() const
Get the attribute table configuration object.
int width
Width of column, or -1 for default width.
A tool button with a dropdown to select the current action.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), const Section section=NoSection) const
Returns the value for setting key.
void setFeatureSelectionManager(QgsIFeatureSelectionManager *featureSelectionManager)
setFeatureSelectionManager
A delegate item class for QgsAttributeTable (see Qt documentation for QItemDelegate).
void setAttributeTableConfig(const QgsAttributeTableConfig &config)
Set the attribute table config which should be used to control the appearance of the attribute table...
Defines the configuration of a column in the attribute table.
qint64 QgsFeatureId
Definition: qgsfeature.h:37
virtual void selectRow(int row)
QUuid id() const
Returns a unique id for this action.
Definition: qgsaction.h:103
virtual void _q_selectRow(int row)
bool nextFeature(QgsFeature &f)
This is a container for configuration of the attribute table.
Is an interface class to abstract feature selection handling.
void closeEvent(QCloseEvent *event) override
Saves geometry to the settings on close.
Represents a vector layer which manages a vector based data sets.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &featureRequest=QgsFeatureRequest())
Query this VectorLayerCache for features.
static QgsMapLayerActionRegistry * mapLayerActionRegistry()
Returns the global map layer action registry, used for registering map layer actions.
Definition: qgsgui.cpp:55
void triggerForFeature(QgsMapLayer *layer, const QgsFeature *feature)
Triggers the action with the specified layer and feature.
An action which can run on map layers.
void keyPressEvent(QKeyEvent *event) override
Called for key press events Disables selection change by only pressing an arrow key.
void contextMenuEvent(QContextMenuEvent *event) override
Is called when the context menu will be shown.
QgsVectorLayerCache * layerCache() const
Returns the layerCache this filter acts on.