QGIS API Documentation  2.99.0-Master (53aba61)
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  , mRowSectionAnchor( 0 )
42  , mCtrlDragSelectionFlag( QItemSelectionModel::Select )
43 {
44  QgsSettings settings;
45  restoreGeometry( settings.value( QStringLiteral( "BetterAttributeTable/geometry" ) ).toByteArray() );
46 
47  //verticalHeader()->setDefaultSectionSize( 20 );
48  horizontalHeader()->setHighlightSections( false );
49 
50  // We need mouse move events to create the action button on hover
51  mTableDelegate = new QgsAttributeTableDelegate( this );
52  setItemDelegate( mTableDelegate );
53 
54  setEditTriggers( QAbstractItemView::AllEditTriggers );
55 
56  setSelectionBehavior( QAbstractItemView::SelectRows );
57  setSelectionMode( QAbstractItemView::ExtendedSelection );
58  setSortingEnabled( true ); // At this point no data is in the model yet, so actually nothing is sorted.
59  horizontalHeader()->setSortIndicatorShown( false ); // So hide the indicator to avoid confusion.
60 
61  verticalHeader()->viewport()->installEventFilter( this );
62 
63  connect( verticalHeader(), &QHeaderView::sectionPressed, this, [ = ]( int row ) { selectRow( row, true ); } );
64  connect( verticalHeader(), &QHeaderView::sectionEntered, this, &QgsAttributeTableView::_q_selectRow );
65  connect( horizontalHeader(), &QHeaderView::sectionResized, this, &QgsAttributeTableView::columnSizeChanged );
66  connect( horizontalHeader(), &QHeaderView::sortIndicatorChanged, this, &QgsAttributeTableView::showHorizontalSortIndicator );
67  connect( QgsGui::mapLayerActionRegistry(), &QgsMapLayerActionRegistry::changed, this, &QgsAttributeTableView::recreateActionWidgets );
68 }
69 
70 bool QgsAttributeTableView::eventFilter( QObject *object, QEvent *event )
71 {
72  if ( object == verticalHeader()->viewport() )
73  {
74  switch ( event->type() )
75  {
76  case QEvent::MouseButtonPress:
77  mFeatureSelectionModel->enableSync( false );
78  break;
79 
80  case QEvent::MouseButtonRelease:
81  mFeatureSelectionModel->enableSync( true );
82  break;
83 
84  default:
85  break;
86  }
87  }
88  return false;
89 }
90 
92 {
93  int i = 0;
94  Q_FOREACH ( const QgsAttributeTableConfig::ColumnConfig &columnConfig, config.columns() )
95  {
96  if ( columnConfig.hidden )
97  continue;
98 
99  if ( columnConfig.width >= 0 )
100  {
101  setColumnWidth( i, columnConfig.width );
102  }
103  else
104  {
105  setColumnWidth( i, horizontalHeader()->defaultSectionSize() );
106  }
107  i++;
108  }
109 }
110 
112 {
113  mFilterModel = filterModel;
114  QTableView::setModel( filterModel );
115 
116  if ( mFilterModel )
117  {
118  connect( mFilterModel, &QObject::destroyed, this, &QgsAttributeTableView::modelDeleted );
119  connect( mTableDelegate, &QgsAttributeTableDelegate::actionColumnItemPainted, this, &QgsAttributeTableView::onActionColumnItemPainted );
120  }
121 
122  delete mFeatureSelectionModel;
123  mFeatureSelectionModel = nullptr;
124 
125  if ( filterModel )
126  {
127  if ( !mFeatureSelectionManager )
128  {
129  mFeatureSelectionManager = new QgsVectorLayerSelectionManager( mFilterModel->layer(), mFilterModel );
130  }
131 
132  mFeatureSelectionModel = new QgsFeatureSelectionModel( mFilterModel, mFilterModel, mFeatureSelectionManager, mFilterModel );
133  setSelectionModel( mFeatureSelectionModel );
134  mTableDelegate->setFeatureSelectionModel( mFeatureSelectionModel );
135  connect( mFeatureSelectionModel, static_cast<void ( QgsFeatureSelectionModel::* )( const QModelIndexList &indexes )>( &QgsFeatureSelectionModel::requestRepaint ),
136  this, static_cast<void ( QgsAttributeTableView::* )( const QModelIndexList &indexes )>( &QgsAttributeTableView::repaintRequested ) );
137  connect( mFeatureSelectionModel, static_cast<void ( QgsFeatureSelectionModel::* )()>( &QgsFeatureSelectionModel::requestRepaint ),
138  this, static_cast<void ( QgsAttributeTableView::* )()>( &QgsAttributeTableView::repaintRequested ) );
139  }
140 }
141 
143 {
144  if ( mFeatureSelectionManager )
145  delete mFeatureSelectionManager;
146 
147  mFeatureSelectionManager = featureSelectionManager;
148 
149  if ( mFeatureSelectionModel )
150  mFeatureSelectionModel->setFeatureSelectionManager( mFeatureSelectionManager );
151 }
152 
153 QWidget *QgsAttributeTableView::createActionWidget( QgsFeatureId fid )
154 {
155  QgsAttributeTableConfig attributeTableConfig = mFilterModel->layer()->attributeTableConfig();
156 
157  QToolButton *toolButton = nullptr;
158  QWidget *container = nullptr;
159 
160  if ( attributeTableConfig.actionWidgetStyle() == QgsAttributeTableConfig::DropDown )
161  {
162  toolButton = new QToolButton();
163  toolButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
164  toolButton->setPopupMode( QToolButton::MenuButtonPopup );
165  container = toolButton;
166  }
167  else
168  {
169  container = new QWidget();
170  container->setLayout( new QHBoxLayout() );
171  container->layout()->setMargin( 0 );
172  }
173 
174  QList< QAction * > actionList;
175  QAction *defaultAction = nullptr;
176 
177  // first add user created layer actions
178  QList<QgsAction> actions = mFilterModel->layer()->actions()->actions( QStringLiteral( "Feature" ) );
179  Q_FOREACH ( const QgsAction &action, actions )
180  {
181  QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : QLatin1String( "" );
182  QAction *act = new QAction( action.icon(), actionTitle, container );
183  act->setToolTip( action.name() );
184  act->setData( "user_action" );
185  act->setProperty( "fid", fid );
186  act->setProperty( "action_id", action.id() );
187  connect( act, &QAction::triggered, this, &QgsAttributeTableView::actionTriggered );
188  actionList << act;
189 
190  if ( mFilterModel->layer()->actions()->defaultAction( QStringLiteral( "AttributeTableRow" ) ).id() == action.id() )
191  defaultAction = act;
192  }
193 
194  // next add any registered actions for this layer
195  Q_FOREACH ( QgsMapLayerAction *mapLayerAction,
196  QgsGui::mapLayerActionRegistry()->mapLayerActions( mFilterModel->layer(),
198  {
199  QAction *action = new QAction( mapLayerAction->icon(), mapLayerAction->text(), container );
200  action->setData( "map_layer_action" );
201  action->setToolTip( mapLayerAction->text() );
202  action->setProperty( "fid", fid );
203  action->setProperty( "action", qVariantFromValue( qobject_cast<QObject *>( mapLayerAction ) ) );
204  connect( action, &QAction::triggered, this, &QgsAttributeTableView::actionTriggered );
205  actionList << action;
206 
207  if ( !defaultAction &&
208  QgsGui::mapLayerActionRegistry()->defaultActionForLayer( mFilterModel->layer() ) == mapLayerAction )
209  defaultAction = action;
210  }
211 
212  if ( !defaultAction && !actionList.isEmpty() )
213  defaultAction = actionList.at( 0 );
214 
215  Q_FOREACH ( QAction *act, actionList )
216  {
217  if ( attributeTableConfig.actionWidgetStyle() == QgsAttributeTableConfig::DropDown )
218  {
219  toolButton->addAction( act );
220 
221  if ( act == defaultAction )
222  toolButton->setDefaultAction( act );
223 
224  container = toolButton;
225  }
226  else
227  {
228  QToolButton *btn = new QToolButton;
229  btn->setDefaultAction( act );
230  container->layout()->addWidget( btn );
231  }
232  }
233 
234  if ( attributeTableConfig.actionWidgetStyle() == QgsAttributeTableConfig::ButtonList )
235  {
236  static_cast< QHBoxLayout * >( container->layout() )->addStretch();
237  }
238 
239  // TODO: Rethink default actions
240 #if 0
241  if ( toolButton && !toolButton->actions().isEmpty() && actions->defaultAction() == -1 )
242  toolButton->setDefaultAction( toolButton->actions().at( 0 ) );
243 #endif
244 
245  return container;
246 }
247 
248 void QgsAttributeTableView::closeEvent( QCloseEvent *e )
249 {
250  Q_UNUSED( e );
251  QgsSettings settings;
252  settings.setValue( QStringLiteral( "BetterAttributeTable/geometry" ), QVariant( saveGeometry() ) );
253 }
254 
255 void QgsAttributeTableView::mousePressEvent( QMouseEvent *event )
256 {
257  setSelectionMode( QAbstractItemView::NoSelection );
258  QTableView::mousePressEvent( event );
259  setSelectionMode( QAbstractItemView::ExtendedSelection );
260 }
261 
263 {
264  setSelectionMode( QAbstractItemView::NoSelection );
265  QTableView::mouseReleaseEvent( event );
266  setSelectionMode( QAbstractItemView::ExtendedSelection );
267 }
268 
269 void QgsAttributeTableView::mouseMoveEvent( QMouseEvent *event )
270 {
271  setSelectionMode( QAbstractItemView::NoSelection );
272  QTableView::mouseMoveEvent( event );
273  setSelectionMode( QAbstractItemView::ExtendedSelection );
274 }
275 
276 void QgsAttributeTableView::keyPressEvent( QKeyEvent *event )
277 {
278  switch ( event->key() )
279  {
280 
281  // Default Qt behavior would be to change the selection.
282  // We don't make it that easy for the user to trash his selection.
283  case Qt::Key_Up:
284  case Qt::Key_Down:
285  case Qt::Key_Left:
286  case Qt::Key_Right:
287  setSelectionMode( QAbstractItemView::NoSelection );
288  QTableView::keyPressEvent( event );
289  setSelectionMode( QAbstractItemView::ExtendedSelection );
290  break;
291 
292  default:
293  QTableView::keyPressEvent( event );
294  break;
295  }
296 }
297 
298 void QgsAttributeTableView::repaintRequested( const QModelIndexList &indexes )
299 {
300  Q_FOREACH ( const QModelIndex &index, indexes )
301  {
302  update( index );
303  }
304 }
305 
307 {
308  setDirtyRegion( viewport()->rect() );
309 }
310 
312 {
313  QItemSelection selection;
314  selection.append( QItemSelectionRange( mFilterModel->index( 0, 0 ), mFilterModel->index( mFilterModel->rowCount() - 1, 0 ) ) );
315  mFeatureSelectionModel->selectFeatures( selection, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
316 }
317 
318 void QgsAttributeTableView::contextMenuEvent( QContextMenuEvent *event )
319 {
320  delete mActionPopup;
321  mActionPopup = nullptr;
322 
323  QModelIndex idx = indexAt( event->pos() );
324  if ( !idx.isValid() )
325  {
326  return;
327  }
328 
329  QgsVectorLayer *vlayer = mFilterModel->layer();
330  if ( !vlayer )
331  return;
332 
333  mActionPopup = new QMenu( this );
334 
335  mActionPopup->addAction( tr( "Select All" ), this, SLOT( selectAll() ), QKeySequence::SelectAll );
336 
337  // let some other parts of the application add some actions
338  emit willShowContextMenu( mActionPopup, idx );
339 
340  if ( !mActionPopup->actions().isEmpty() )
341  {
342  mActionPopup->popup( event->globalPos() );
343  }
344 }
345 
347 {
348  selectRow( row, true );
349 }
350 
352 {
353  selectRow( row, false );
354 }
355 
356 void QgsAttributeTableView::modelDeleted()
357 {
358  mFilterModel = nullptr;
359  mFeatureSelectionManager = nullptr;
360  mFeatureSelectionModel = nullptr;
361 }
362 
363 void QgsAttributeTableView::selectRow( int row, bool anchor )
364 {
365  if ( selectionBehavior() == QTableView::SelectColumns
366  || ( selectionMode() == QTableView::SingleSelection
367  && selectionBehavior() == QTableView::SelectItems ) )
368  return;
369 
370  if ( row >= 0 && row < model()->rowCount() )
371  {
372  int column = horizontalHeader()->logicalIndexAt( isRightToLeft() ? viewport()->width() : 0 );
373  QModelIndex index = model()->index( row, column );
374  QItemSelectionModel::SelectionFlags command = selectionCommand( index );
375  selectionModel()->setCurrentIndex( index, QItemSelectionModel::NoUpdate );
376  if ( ( anchor && !( command & QItemSelectionModel::Current ) )
377  || ( selectionMode() == QTableView::SingleSelection ) )
378  mRowSectionAnchor = row;
379 
380  if ( selectionMode() != QTableView::SingleSelection
381  && command.testFlag( QItemSelectionModel::Toggle ) )
382  {
383  if ( anchor )
384  mCtrlDragSelectionFlag = mFeatureSelectionModel->isSelected( index )
385  ? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
386  command &= ~QItemSelectionModel::Toggle;
387  command |= mCtrlDragSelectionFlag;
388  if ( !anchor )
389  command |= QItemSelectionModel::Current;
390  }
391 
392  QModelIndex tl = model()->index( std::min( mRowSectionAnchor, row ), 0 );
393  QModelIndex br = model()->index( std::max( mRowSectionAnchor, row ), model()->columnCount() - 1 );
394  if ( verticalHeader()->sectionsMoved() && tl.row() != br.row() )
395  setSelection( visualRect( tl ) | visualRect( br ), command );
396  else
397  mFeatureSelectionModel->selectFeatures( QItemSelection( tl, br ), command );
398  }
399 }
400 
401 void QgsAttributeTableView::showHorizontalSortIndicator()
402 {
403  horizontalHeader()->setSortIndicatorShown( true );
404 }
405 
406 void QgsAttributeTableView::actionTriggered()
407 {
408  QAction *action = qobject_cast<QAction *>( sender() );
409  QgsFeatureId fid = action->property( "fid" ).toLongLong();
410 
411  QgsFeature f;
412  mFilterModel->layerCache()->getFeatures( QgsFeatureRequest( fid ) ).nextFeature( f );
413 
414  if ( action->data().toString() == QLatin1String( "user_action" ) )
415  {
416  mFilterModel->layer()->actions()->doAction( action->property( "action_id" ).toString(), f );
417  }
418  else if ( action->data().toString() == QLatin1String( "map_layer_action" ) )
419  {
420  QObject *object = action->property( "action" ).value<QObject *>();
421  QgsMapLayerAction *layerAction = qobject_cast<QgsMapLayerAction *>( object );
422  if ( layerAction )
423  {
424  layerAction->triggerForFeature( mFilterModel->layer(), &f );
425  }
426  }
427 }
428 
429 void QgsAttributeTableView::columnSizeChanged( int index, int oldWidth, int newWidth )
430 {
431  Q_UNUSED( oldWidth )
432  emit columnResized( index, newWidth );
433 }
434 
435 void QgsAttributeTableView::onActionColumnItemPainted( const QModelIndex &index )
436 {
437  if ( !indexWidget( index ) )
438  {
439  QWidget *widget = createActionWidget( mFilterModel->data( index, QgsAttributeTableModel::FeatureIdRole ).toLongLong() );
440  mActionWidgets.insert( index, widget );
441  setIndexWidget( index, widget );
442  }
443 }
444 
445 void QgsAttributeTableView::recreateActionWidgets()
446 {
447  QMap< QModelIndex, QWidget * > newWidgets;
448  QMap< QModelIndex, QWidget * >::const_iterator it = mActionWidgets.constBegin();
449  for ( ; it != mActionWidgets.constEnd(); ++it )
450  {
451  it.value()->deleteLater(); //?
452  QWidget *widget = createActionWidget( mFilterModel->data( it.key(), QgsAttributeTableModel::FeatureIdRole ).toLongLong() );
453  newWidgets.insert( it.key(), widget );
454  setIndexWidget( it.key(), widget );
455  }
456  mActionWidgets = newWidgets;
457 }
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:98
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:118
QString name() const
The name of the action. This may be a longer description.
Definition: qgsaction.h:95
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 drop-down 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:105
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:64
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.