16#include <QDesktopServices>
42 restoreGeometry( settings.
value( QStringLiteral(
"BetterAttributeTable/geometry" ) ).toByteArray() );
45 horizontalHeader()->setHighlightSections(
false );
49 setItemDelegate( mTableDelegate );
51 setEditTriggers( QAbstractItemView::AllEditTriggers );
53 setSelectionBehavior( QAbstractItemView::SelectRows );
54 setSelectionMode( QAbstractItemView::ExtendedSelection );
55 setSortingEnabled(
true );
56 horizontalHeader()->setSortIndicatorShown(
false );
58 setHorizontalScrollMode( QAbstractItemView::ScrollPerPixel );
60 verticalHeader()->viewport()->installEventFilter(
this );
62 connect( verticalHeader(), &QHeaderView::sectionPressed,
this, [ = ](
int row ) {
selectRow( row,
true ); } );
64 connect( horizontalHeader(), &QHeaderView::sectionResized,
this, &QgsAttributeTableView::columnSizeChanged );
65 connect( horizontalHeader(), &QHeaderView::sortIndicatorChanged,
this, &QgsAttributeTableView::showHorizontalSortIndicator );
71 if (
object == verticalHeader()->viewport() )
73 switch ( event->type() )
75 case QEvent::MouseButtonPress:
79 case QEvent::MouseButtonRelease:
87 return QTableView::eventFilter(
object, event );
93 const auto constColumns = config.
columns();
94 QMap<QString, int> columns;
97 if ( columnConfig.hidden )
100 if ( columnConfig.width >= 0 )
102 setColumnWidth( i, columnConfig.width );
106 setColumnWidth( i, horizontalHeader()->defaultSectionSize() );
108 columns.insert( columnConfig.name, i );
114 horizontalHeader()->setSortIndicatorShown(
false );
121 if ( sortExp.isField() )
123 const QStringList refCols { sortExp.referencedColumns().values() };
124 horizontalHeader()->setSortIndicatorShown(
true );
125 horizontalHeader()->setSortIndicator( columns.value( refCols.constFirst() ), config.
sortOrder() );
138 QModelIndexList indexList;
141 const QModelIndex index = mFilterModel->
fidToIndex(
id );
145 std::sort( indexList.begin(), indexList.end() );
146 QList<QgsFeatureId> ids;
147 for (
const QModelIndex &index : indexList )
157 mFilterModel = filterModel;
158 QTableView::setModel( mFilterModel );
162 connect( mFilterModel, &QObject::destroyed,
this, &QgsAttributeTableView::modelDeleted );
166 delete mFeatureSelectionModel;
167 mFeatureSelectionModel =
nullptr;
171 if ( !mFeatureSelectionManager )
174 mFeatureSelectionManager = mOwnedFeatureSelectionManager;
177 mFeatureSelectionModel =
new QgsFeatureSelectionModel( mFilterModel, mFilterModel, mFeatureSelectionManager, mFilterModel );
178 setSelectionModel( mFeatureSelectionModel );
193 mFeatureSelectionManager = featureSelectionManager;
195 if ( mFeatureSelectionModel )
199 if ( mOwnedFeatureSelectionManager )
201 mOwnedFeatureSelectionManager->deleteLater();
202 mOwnedFeatureSelectionManager =
nullptr;
206QWidget *QgsAttributeTableView::createActionWidget(
QgsFeatureId fid )
210 QToolButton *toolButton =
nullptr;
211 QWidget *container =
nullptr;
215 toolButton =
new QToolButton();
216 toolButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
217 toolButton->setPopupMode( QToolButton::MenuButtonPopup );
218 container = toolButton;
222 container =
new QWidget();
223 container->setLayout(
new QHBoxLayout() );
224 container->layout()->setContentsMargins( 0, 0, 0, 0 );
227 QList< QAction * > actionList;
228 QAction *defaultAction =
nullptr;
231 const QList<QgsAction> actions = mFilterModel->
layer()->
actions()->
actions( QStringLiteral(
"Feature" ) );
232 const auto constActions = actions;
233 for (
const QgsAction &action : constActions )
235 if ( !mFilterModel->
layer()->
isEditable() && action.isEnabledOnlyWhenEditable() )
238 const QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : QString();
239 QAction *act =
new QAction( action.icon(), actionTitle, container );
240 act->setToolTip( action.name() );
241 act->setData(
"user_action" );
242 act->setProperty(
"fid", fid );
243 act->setProperty(
"action_id", action.id() );
244 connect( act, &QAction::triggered,
this, &QgsAttributeTableView::actionTriggered );
256 QAction *action =
new QAction( mapLayerAction->icon(), mapLayerAction->text(), container );
257 action->setData(
"map_layer_action" );
258 action->setToolTip( mapLayerAction->text() );
259 action->setProperty(
"fid", fid );
260 action->setProperty(
"action", QVariant::fromValue( qobject_cast<QObject *>( mapLayerAction ) ) );
261 connect( action, &QAction::triggered,
this, &QgsAttributeTableView::actionTriggered );
262 actionList << action;
264 if ( !defaultAction &&
266 defaultAction = action;
269 if ( !defaultAction && !actionList.isEmpty() )
270 defaultAction = actionList.at( 0 );
272 const auto constActionList = actionList;
273 for ( QAction *act : constActionList )
277 toolButton->addAction( act );
279 if ( act == defaultAction )
280 toolButton->setDefaultAction( act );
282 container = toolButton;
286 QToolButton *btn =
new QToolButton;
287 btn->setDefaultAction( act );
288 container->layout()->addWidget( btn );
294 static_cast< QHBoxLayout *
>( container->layout() )->addStretch();
299 if ( toolButton && !toolButton->actions().isEmpty() && actions->defaultAction() == -1 )
300 toolButton->setDefaultAction( toolButton->actions().at( 0 ) );
310 settings.
setValue( QStringLiteral(
"BetterAttributeTable/geometry" ), QVariant( saveGeometry() ) );
315 setSelectionMode( QAbstractItemView::NoSelection );
316 QTableView::mousePressEvent( event );
317 setSelectionMode( QAbstractItemView::ExtendedSelection );
322 setSelectionMode( QAbstractItemView::NoSelection );
323 QTableView::mouseReleaseEvent( event );
324 setSelectionMode( QAbstractItemView::ExtendedSelection );
325 if ( event->modifiers() == Qt::ControlModifier )
327 const QModelIndex index = indexAt( event->pos() );
328 const QVariant data = model()->data( index, Qt::DisplayRole );
329 if ( data.type() == QVariant::String )
331 const QString textVal = data.toString();
334 QDesktopServices::openUrl( QUrl( textVal ) );
342 setSelectionMode( QAbstractItemView::NoSelection );
343 QTableView::mouseMoveEvent( event );
344 setSelectionMode( QAbstractItemView::ExtendedSelection );
349 switch ( event->key() )
358 setSelectionMode( QAbstractItemView::NoSelection );
359 QTableView::keyPressEvent( event );
360 setSelectionMode( QAbstractItemView::ExtendedSelection );
364 QTableView::keyPressEvent( event );
371 const auto constIndexes = indexes;
372 for (
const QModelIndex &index : constIndexes )
380 setDirtyRegion( viewport()->rect() );
385 QItemSelection selection;
386 selection.append( QItemSelectionRange( mFilterModel->index( 0, 0 ), mFilterModel->index( mFilterModel->rowCount() - 1, 0 ) ) );
387 mFeatureSelectionModel->
selectFeatures( selection, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
393 mActionPopup =
nullptr;
395 const QModelIndex idx = mFilterModel->
mapToMaster( indexAt( event->pos() ) );
396 if ( !idx.isValid() )
405 mActionPopup =
new QMenu(
this );
407 QAction *selectAllAction = mActionPopup->addAction( tr(
"Select All" ) );
408 selectAllAction->setShortcut( QKeySequence::SelectAll );
414 if ( !mActionPopup->actions().isEmpty() )
416 mActionPopup->popup( event->globalPos() );
430void QgsAttributeTableView::modelDeleted()
432 mFilterModel =
nullptr;
433 mFeatureSelectionManager =
nullptr;
434 mFeatureSelectionModel =
nullptr;
439 if ( selectionBehavior() == QTableView::SelectColumns
440 || ( selectionMode() == QTableView::SingleSelection
441 && selectionBehavior() == QTableView::SelectItems ) )
444 if ( row >= 0 && row < model()->rowCount() )
446 const int column = horizontalHeader()->logicalIndexAt( isRightToLeft() ? viewport()->width() : 0 );
447 const QModelIndex index = model()->index( row, column );
448 QItemSelectionModel::SelectionFlags command = selectionCommand( index );
449 selectionModel()->setCurrentIndex( index, QItemSelectionModel::NoUpdate );
450 if ( ( anchor && !( command & QItemSelectionModel::Current ) )
451 || ( selectionMode() == QTableView::SingleSelection ) )
452 mRowSectionAnchor = row;
454 if ( selectionMode() != QTableView::SingleSelection
455 && command.testFlag( QItemSelectionModel::Toggle ) )
458 mCtrlDragSelectionFlag = mFeatureSelectionModel->
isSelected( index )
459 ? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
460 command &= ~QItemSelectionModel::Toggle;
461 command |= mCtrlDragSelectionFlag;
463 command |= QItemSelectionModel::Current;
466 const QModelIndex tl = model()->index( std::min( mRowSectionAnchor, row ), 0 );
467 const QModelIndex br = model()->index( std::max( mRowSectionAnchor, row ), model()->columnCount() - 1 );
468 if ( verticalHeader()->sectionsMoved() && tl.row() != br.row() )
469 setSelection( visualRect( tl ) | visualRect( br ), command );
471 mFeatureSelectionModel->
selectFeatures( QItemSelection( tl, br ), command );
475void QgsAttributeTableView::showHorizontalSortIndicator()
477 horizontalHeader()->setSortIndicatorShown(
true );
480void QgsAttributeTableView::actionTriggered()
482 QAction *action = qobject_cast<QAction *>( sender() );
483 const QgsFeatureId fid = action->property(
"fid" ).toLongLong();
488 if ( action->data().toString() == QLatin1String(
"user_action" ) )
492 else if ( action->data().toString() == QLatin1String(
"map_layer_action" ) )
494 QObject *
object = action->property(
"action" ).value<QObject *>();
500 layerAction->triggerForFeature( mFilterModel->
layer(), f );
502 layerAction->triggerForFeature( mFilterModel->
layer(), f, context );
507void QgsAttributeTableView::columnSizeChanged(
int index,
int oldWidth,
int newWidth )
513void QgsAttributeTableView::onActionColumnItemPainted(
const QModelIndex &index )
515 if ( !indexWidget( index ) )
518 mActionWidgets.insert( index, widget );
519 setIndexWidget( index, widget );
523void QgsAttributeTableView::recreateActionWidgets()
525 QMap< QModelIndex, QWidget * >::const_iterator it = mActionWidgets.constBegin();
526 for ( ; it != mActionWidgets.constEnd(); ++it )
531 setIndexWidget( it.key(),
nullptr );
533 mActionWidgets.clear();
538 const QModelIndex index = mFilterModel->
fidToIndex( fid );
540 if ( !index.isValid() )
545 const QModelIndex selectionIndex = index.sibling( index.row(), col );
547 if ( !selectionIndex.isValid() )
550 selectionModel()->setCurrentIndex( index, QItemSelectionModel::SelectCurrent );
555 QWidget *editor = indexWidget( currentIndex() );
556 commitData( editor );
557 closeEditor( editor, QAbstractItemDelegate::NoHint );
@ SingleFeature
Action targets a single feature from a layer.
QList< QgsAction > actions(const QString &actionScope=QString()) const
Returns a list of actions that are available in the given action scope.
void doAction(QUuid actionId, const QgsFeature &feature, int defaultValueIndex=0, const QgsExpressionContextScope &scope=QgsExpressionContextScope())
Does the given action.
QgsAction defaultAction(const QString &actionScope)
Each scope can have a default action.
Utility class that encapsulates an action based on vector attributes.
QUuid id() const
Returns a unique id for this action.
This is a container for configuration of the attribute table.
Qt::SortOrder sortOrder() const
Gets the sort order.
QVector< QgsAttributeTableConfig::ColumnConfig > columns() const
Gets the list with all columns and their configuration.
@ DropDown
A tool button with a drop-down to select the current action.
@ ButtonList
A list of buttons.
ActionWidgetStyle actionWidgetStyle() const
Gets the style of the action widget.
QString sortExpression() const
Gets the expression used for sorting.
A delegate item class for QgsAttributeTable (see Qt documentation for QItemDelegate).
void actionColumnItemPainted(const QModelIndex &index) const
Emitted when an action column item is painted.
void setFeatureSelectionModel(QgsFeatureSelectionModel *featureSelectionModel)
QgsVectorLayerCache * layerCache() const
Returns the layerCache this filter acts on.
QModelIndex fidToIndex(QgsFeatureId fid) override
QVariant data(const QModelIndex &index, int role) const override
QModelIndex mapToMaster(const QModelIndex &proxyIndex) const
QgsVectorLayer * layer() const
Returns the layer this filter acts on.
@ FeatureId
Get the feature id of the feature in this row.
Provides a table view of features of a QgsVectorLayer.
void willShowContextMenu(QMenu *menu, const QModelIndex &atIndex)
Emitted in order to provide a hook to add additional* menu entries to the context menu.
QList< QgsFeatureId > selectedFeaturesIds() const
Returns the selected features in the attribute table in table sorted order.
void setFeatureSelectionManager(QgsIFeatureSelectionManager *featureSelectionManager)
setFeatureSelectionManager
void mouseMoveEvent(QMouseEvent *event) override
Called for mouse move events on a table cell.
virtual void selectRow(int row)
QgsAttributeTableView(QWidget *parent=nullptr)
Constructor for QgsAttributeTableView.
void selectAll() override
void scrollToFeature(const QgsFeatureId &fid, int column=-1)
Scroll to a feature with a given fid.
void mouseReleaseEvent(QMouseEvent *event) override
Called for mouse release events on a table cell.
void contextMenuEvent(QContextMenuEvent *event) override
Is called when the context menu will be shown.
virtual void _q_selectRow(int row)
void closeEvent(QCloseEvent *event) override
Saves geometry to the settings on close.
void mousePressEvent(QMouseEvent *event) override
Called for mouse press events on a table cell.
void closeCurrentEditor()
Closes the editor delegate for the current item, committing its changes to the model.
void keyPressEvent(QKeyEvent *event) override
Called for key press events Disables selection change by only pressing an arrow key.
void setAttributeTableConfig(const QgsAttributeTableConfig &config)
Set the attribute table config which should be used to control the appearance of the attribute table.
void columnResized(int column, int width)
Emitted when a column in the view has been resized.
bool eventFilter(QObject *object, QEvent *event) override
This event filter is installed on the verticalHeader to intercept mouse press and release events.
virtual void setModel(QgsAttributeTableFilterModel *filterModel)
Class for parsing and evaluation of expressions (formerly called "search strings").
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
This class wraps a request for features to a vector layer (or directly its vector data provider).
void enableSync(bool enable)
Enables or disables synchronisation to the QgsVectorLayer When synchronisation is disabled,...
virtual void selectFeatures(const QItemSelection &selection, QItemSelectionModel::SelectionFlags command)
Select features on this table.
virtual bool isSelected(QgsFeatureId fid)
Returns the selection status of a given feature id.
virtual void setFeatureSelectionManager(QgsIFeatureSelectionManager *featureSelectionManager)
void requestRepaint()
Request a repaint of the visible items of connected views.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
static QgsMapLayerActionRegistry * mapLayerActionRegistry()
Returns the global map layer action registry, used for registering map layer actions.
Is an interface class to abstract feature selection handling.
virtual const QgsFeatureIds & selectedFeatureIds() const =0
Returns reference to identifiers of selected features.
Encapsulates the context in which a QgsMapLayerAction action is executed.
void changed()
Triggered when an action is added or removed from the registry.
QList< QgsMapLayerAction * > mapLayerActions(QgsMapLayer *layer, Qgis::MapLayerActionTargets targets=Qgis::MapLayerActionTarget::AllActions, const QgsMapLayerActionContext &context=QgsMapLayerActionContext())
Returns the map layer actions which can run on the specified layer.
An action which can run on map layers The class can be used in two manners:
void editingStopped()
Emitted when edited changes have been successfully written to the data provider.
void editingStarted()
Emitted when editing on this layer has started.
This class is a composition of two QSettings instances:
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
static bool isUrl(const QString &string)
Returns whether the string is a URL (http,https,ftp,file)
A QTableView subclass with QGIS specific tweaks and improvements.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &featureRequest=QgsFeatureRequest())
Query this VectorLayerCache for features.
Represents a vector layer which manages a vector based data sets.
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
QgsActionManager * actions()
Returns all layer actions defined on this layer.
void readOnlyChanged()
Emitted when the read only state of this layer is changed.
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Defines the configuration of a column in the attribute table.