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() );
129 horizontalHeader()->setSortIndicatorShown(
false );
142 QModelIndexList indexList;
145 const QModelIndex index = mFilterModel->
fidToIndex(
id );
149 std::sort( indexList.begin(), indexList.end() );
150 QList<QgsFeatureId> ids;
151 for (
const QModelIndex &index : indexList )
161 mFilterModel = filterModel;
162 QTableView::setModel( mFilterModel );
166 connect( mFilterModel, &QObject::destroyed,
this, &QgsAttributeTableView::modelDeleted );
170 delete mFeatureSelectionModel;
171 mFeatureSelectionModel =
nullptr;
175 if ( !mFeatureSelectionManager )
178 mFeatureSelectionManager = mOwnedFeatureSelectionManager;
181 mFeatureSelectionModel =
new QgsFeatureSelectionModel( mFilterModel, mFilterModel, mFeatureSelectionManager, mFilterModel );
182 setSelectionModel( mFeatureSelectionModel );
197 mFeatureSelectionManager = featureSelectionManager;
199 if ( mFeatureSelectionModel )
203 if ( mOwnedFeatureSelectionManager )
205 mOwnedFeatureSelectionManager->deleteLater();
206 mOwnedFeatureSelectionManager =
nullptr;
210QWidget *QgsAttributeTableView::createActionWidget(
QgsFeatureId fid )
214 QToolButton *toolButton =
nullptr;
215 QWidget *container =
nullptr;
219 toolButton =
new QToolButton();
220 toolButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
221 toolButton->setPopupMode( QToolButton::MenuButtonPopup );
222 container = toolButton;
226 container =
new QWidget();
227 container->setLayout(
new QHBoxLayout() );
228 container->layout()->setContentsMargins( 0, 0, 0, 0 );
231 QList< QAction * > actionList;
232 QAction *defaultAction =
nullptr;
235 const QList<QgsAction> actions = mFilterModel->
layer()->
actions()->
actions( QStringLiteral(
"Feature" ) );
236 const auto constActions = actions;
237 for (
const QgsAction &action : constActions )
239 if ( !mFilterModel->
layer()->
isEditable() && action.isEnabledOnlyWhenEditable() )
242 const QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : QString();
243 QAction *act =
new QAction( action.icon(), actionTitle, container );
244 act->setToolTip( action.name() );
245 act->setData(
"user_action" );
246 act->setProperty(
"fid", fid );
247 act->setProperty(
"action_id", action.id() );
248 connect( act, &QAction::triggered,
this, &QgsAttributeTableView::actionTriggered );
260 QAction *action =
new QAction( mapLayerAction->icon(), mapLayerAction->text(), container );
261 action->setData(
"map_layer_action" );
262 action->setToolTip( mapLayerAction->text() );
263 action->setProperty(
"fid", fid );
264 action->setProperty(
"action", QVariant::fromValue( qobject_cast<QObject *>( mapLayerAction ) ) );
265 connect( action, &QAction::triggered,
this, &QgsAttributeTableView::actionTriggered );
266 actionList << action;
268 if ( !defaultAction &&
270 defaultAction = action;
273 if ( !defaultAction && !actionList.isEmpty() )
274 defaultAction = actionList.at( 0 );
276 const auto constActionList = actionList;
277 for ( QAction *act : constActionList )
281 toolButton->addAction( act );
283 if ( act == defaultAction )
284 toolButton->setDefaultAction( act );
286 container = toolButton;
290 QToolButton *btn =
new QToolButton;
291 btn->setDefaultAction( act );
292 container->layout()->addWidget( btn );
298 static_cast< QHBoxLayout *
>( container->layout() )->addStretch();
303 if ( toolButton && !toolButton->actions().isEmpty() && actions->defaultAction() == -1 )
304 toolButton->setDefaultAction( toolButton->actions().at( 0 ) );
314 settings.
setValue( QStringLiteral(
"BetterAttributeTable/geometry" ), QVariant( saveGeometry() ) );
319 setSelectionMode( QAbstractItemView::NoSelection );
320 QTableView::mousePressEvent( event );
321 setSelectionMode( QAbstractItemView::ExtendedSelection );
326 setSelectionMode( QAbstractItemView::NoSelection );
327 QTableView::mouseReleaseEvent( event );
328 setSelectionMode( QAbstractItemView::ExtendedSelection );
329 if ( event->modifiers() == Qt::ControlModifier )
331 const QModelIndex index = indexAt( event->pos() );
332 const QVariant data = model()->data( index, Qt::DisplayRole );
333 if ( data.userType() == QMetaType::Type::QString )
335 const QString textVal = data.toString();
338 QDesktopServices::openUrl( QUrl( textVal ) );
346 setSelectionMode( QAbstractItemView::NoSelection );
347 QTableView::mouseMoveEvent( event );
348 setSelectionMode( QAbstractItemView::ExtendedSelection );
353 switch ( event->key() )
362 setSelectionMode( QAbstractItemView::NoSelection );
363 QTableView::keyPressEvent( event );
364 setSelectionMode( QAbstractItemView::ExtendedSelection );
368 QTableView::keyPressEvent( event );
375 const auto constIndexes = indexes;
376 for (
const QModelIndex &index : constIndexes )
384 setDirtyRegion( viewport()->rect() );
389 QItemSelection selection;
390 selection.append( QItemSelectionRange( mFilterModel->index( 0, 0 ), mFilterModel->index( mFilterModel->rowCount() - 1, 0 ) ) );
391 mFeatureSelectionModel->
selectFeatures( selection, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
397 mActionPopup =
nullptr;
399 const QModelIndex idx = mFilterModel->
mapToMaster( indexAt( event->pos() ) );
400 if ( !idx.isValid() )
409 mActionPopup =
new QMenu(
this );
411 QAction *selectAllAction = mActionPopup->addAction( tr(
"Select All" ) );
412 selectAllAction->setShortcut( QKeySequence::SelectAll );
418 if ( !mActionPopup->actions().isEmpty() )
420 mActionPopup->popup( event->globalPos() );
434void QgsAttributeTableView::modelDeleted()
436 mFilterModel =
nullptr;
437 mFeatureSelectionManager =
nullptr;
438 mFeatureSelectionModel =
nullptr;
443 if ( selectionBehavior() == QTableView::SelectColumns
444 || ( selectionMode() == QTableView::SingleSelection
445 && selectionBehavior() == QTableView::SelectItems ) )
448 if ( row >= 0 && row < model()->rowCount() )
450 const int column = horizontalHeader()->logicalIndexAt( isRightToLeft() ? viewport()->width() : 0 );
451 const QModelIndex index = model()->index( row, column );
452 QItemSelectionModel::SelectionFlags command = selectionCommand( index );
453 selectionModel()->setCurrentIndex( index, QItemSelectionModel::NoUpdate );
454 if ( ( anchor && !( command & QItemSelectionModel::Current ) )
455 || ( selectionMode() == QTableView::SingleSelection ) )
456 mRowSectionAnchor = row;
458 if ( selectionMode() != QTableView::SingleSelection
459 && command.testFlag( QItemSelectionModel::Toggle ) )
462 mCtrlDragSelectionFlag = mFeatureSelectionModel->
isSelected( index )
463 ? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
464 command &= ~QItemSelectionModel::Toggle;
465 command |= mCtrlDragSelectionFlag;
467 command |= QItemSelectionModel::Current;
470 const QModelIndex tl = model()->index( std::min( mRowSectionAnchor, row ), 0 );
471 const QModelIndex br = model()->index( std::max( mRowSectionAnchor, row ), model()->columnCount() - 1 );
472 if ( verticalHeader()->sectionsMoved() && tl.row() != br.row() )
473 setSelection( visualRect( tl ) | visualRect( br ), command );
475 mFeatureSelectionModel->
selectFeatures( QItemSelection( tl, br ), command );
479void QgsAttributeTableView::showHorizontalSortIndicator()
481 horizontalHeader()->setSortIndicatorShown(
true );
484void QgsAttributeTableView::actionTriggered()
486 QAction *action = qobject_cast<QAction *>( sender() );
487 const QgsFeatureId fid = action->property(
"fid" ).toLongLong();
492 if ( action->data().toString() == QLatin1String(
"user_action" ) )
496 else if ( action->data().toString() == QLatin1String(
"map_layer_action" ) )
498 QObject *
object = action->property(
"action" ).value<QObject *>();
504 layerAction->triggerForFeature( mFilterModel->
layer(), f );
506 layerAction->triggerForFeature( mFilterModel->
layer(), f, context );
511void QgsAttributeTableView::columnSizeChanged(
int index,
int oldWidth,
int newWidth )
517void QgsAttributeTableView::onActionColumnItemPainted(
const QModelIndex &index )
519 if ( !indexWidget( index ) )
522 mActionWidgets.insert( index, widget );
523 setIndexWidget( index, widget );
527void QgsAttributeTableView::recreateActionWidgets()
529 QMap< QModelIndex, QWidget * >::const_iterator it = mActionWidgets.constBegin();
530 for ( ; it != mActionWidgets.constEnd(); ++it )
535 setIndexWidget( it.key(),
nullptr );
537 mActionWidgets.clear();
542 const QModelIndex index = mFilterModel->
fidToIndex( fid );
544 if ( !index.isValid() )
549 const QModelIndex selectionIndex = index.sibling( index.row(), col );
551 if ( !selectionIndex.isValid() )
554 selectionModel()->setCurrentIndex( index, QItemSelectionModel::SelectCurrent );
559 QWidget *editor = indexWidget( currentIndex() );
560 commitData( editor );
561 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.