Qt model view framework: QAbstractItemModel, QAbstractItemView

QAbstractItemModel

I. Overview

The QAbstractItemModel class defines the standard interface that item models must use to be able to interoperate with other components in the model/view framework. The correct usage is to subclass it to create new models.

This class is used as the underlying data model for item view elements in QML or item view classes in the Qt Widgets module.

If you need a model to be used with item views, such as QML's list view element or the C++ widgets QListView or QTableView, you should consider subclassing QAbstractListModel or QAbstractTableModel instead of this class.

The underlying data model is exposed to views and delegates as a hierarchy of tables. If you don't use hierarchies, then the model is a simple row and list.

Each item has a unique index specified by QModelIndex.

 

1.1. Subclassing

When inheriting QAbstractItemModel, you must at least implement:

index()
parent()
rowCount()
columnCount()
data()

These functions are used in all read-only models and form the basis of editable models.

To enable editing in a model, you must also implement:

setData()

flags() (to ensure that ItemIsEditable is returned)

To control how the model title is displayed, you can:

headerData()
setHeaderData()

When reimplementing the setData() and setHeaderData() functions, dataChanged() and headerDataChanged() must be signaled explicitly, respectively.

2. Member type

1. enum class QAbstractItemModel::CheckIndexOption: This enumeration can be used to control the check performed by checkIndex() (this function checks whether index is a legal model index for this model).

  • NoOption: No option is specified.
  • IndexIsValid: The model index passed to checkIndex() is checked as a valid model index.
  • DoNotUseParent: Do not perform any checks involving the use of the parent of the index passed to checkIndex().
  • ParentIsInvalid: The parent of the model index passed to checkIndex() is checked as an invalid model index. This option is ignored if both this option and DoNotUseParent are specified.

2. enum QAbstractItemModel::LayoutChangeHint: This enumeration describes how the model changes the layout.

  • NoLayoutChangeHint: None.
  • VerticalSortHint: Rows are being sorted.
  • HorizontalSortHint: Columns are being sorted.

3. Member functions

3.1. Private signal

Private signals can only be emitted by QAbstractItemModel implementations, not explicitly in subclass code.

Private signals can be used for signal connections, but cannot be emitted by users.

1、[私有] void columnsAboutToBeInserted(const QModelIndex &parent, int first, int last)

This signal is emitted before the column is inserted into the model. The new item will be between first and last under the given parent.

Components connected to this signal use it to accommodate changes in model size.

2、[私有] void columnsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationColumn)

This signal is emitted before the column is moved within the model. The items to be moved are those between sourceStart and sourceEnd under the given sourceParent item. They will be moved to destinationParent, starting from the destinationColumn column.

Components connected to this signal use it to accommodate changes in model size.

3、[私有] void columnsAboutToBeRemoved(const QModelIndex &parent, int first, int last)

This signal is emitted before the column is removed from the model. The items to delete are those between first and last under the given parent.

Components connected to this signal use it to accommodate changes in model size.

4、[私有] void columnsInserted(const QModelIndex &parent, int first, int last)

This signal is emitted after a column has been inserted into the model. The new items are the items between first and last under the given parent.

Components connected to this signal use it to accommodate changes in model size.

5、[私有] void columnsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int column)

This signal is emitted after a column has been moved within the model. Items between start and end under parent have been moved to the destination starting at column column.

Components connected to this signal use it to accommodate changes in model size.

6、[私有] void columnsRemoved(const QModelIndex &parent, int first, int last)

This signal is emitted when a column is removed from the model. The deleted items are the items between first and last under given parent.

Components connected to this signal use it to accommodate changes in model size.

7. [Private] void modelAboutToBeReset()

This signal is emitted when beginResetModel() is called, before the model's internal state (for example, the persistent model index) is invalidated.

8. [Private] void modelReset()

This signal is emitted when endResetModel() is called after the model's internal state (for example, a persistent model index) has expired.

9、[私有] void rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)

This signal is emitted before a row is inserted into the model. New items will be positioned between start and end under the given parent.

Components connected to this signal use it to accommodate changes in model size.

10、[私有] void rowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)

This signal is emitted before the row moves within the model. The items to be moved are those between sourceStart and sourceEnd under the given sourceParent item. They will be moved to the destinationParent row, starting at destinationRow.

Components connected to this signal use it to accommodate changes in model size.

11、[私有] void rowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)

This signal is emitted just before a row is removed from the model. The items to be removed are those between first and last under the given parent.

Components connected to this signal use it to accommodate changes in model size.

12、[私有] void rowsInserted(const QModelIndex &parent, int first, int last)

This signal is emitted after a row has been inserted into the model. The new items are the items between first and last under the given parent.

Components connected to this signal use it to accommodate changes in model size.

13、[私有] void rowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row)

This signal is emitted after a row has been moved within the model. Items between start and end under the given parent have been moved to destination starting at row row.

Components connected to this signal use it to accommodate changes in model size.

14、[私有] void rowsRemoved(const QModelIndex &parent, int first, int last)

This signal is emitted after a row has been removed from the model. The deleted items are the items between first and last under the given parent.

Components connected to this signal use it to accommodate changes in model size.

3.2. Non-private signals

1、void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &roles = QList<int>())

This signal is emitted whenever data in an existing item changes.

If the items belong to the same parent, the affected items are those between topLeft and bottomRight. The behavior is undefined if the items do not have the same parent.

This signal must be explicitly emitted when reimplementing the setData() function.

roles can be used to specify which data roles are actually modified. The order of the elements in roles does not have any relevance.

2、void headerDataChanged(Qt::Orientation orientation, int first, int last)

This signal is emitted whenever the title is changed. orientation indicates whether the horizontal or vertical heading has changed. The part from first to last in the title needs to be updated.

This signal must be explicitly emitted when reimplementing the setHeaderData() function.

You don't need to emit this signal if you want to change the number of columns or rows.

3、void layoutAboutToBeChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)

This signal is emitted before the model layout changes. Components connected to this signal use it to adapt to changes in the model's layout.

Subclasses should update the persistent model index after issuing layoutAboutToBeChanged().

The parent parameter is used to provide more specific notifications about which parts of the model's layout are changing, an empty list indicates that the layout of the entire model has changed. The order of the elements in the list is not important. The hint parameter is used to hint what happens when the model is re-layouted.

4、void layoutChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)

This signal is emitted whenever the layout of items exposed by the model changes (for example, when the model has been sorted). When the view receives this signal, it should update the item's layout to reflect this change.

When subclassing QAbstractItemModel or QAbstractProxyModel, be sure to issue layoutAboutToBeChanged() before changing the order of items or changing the data structures exposed to the view, and issue layoutChanged() after changing the layout.

The parent parameter is used to provide more specific notifications about which parts of the model's layout are changing, an empty list indicates that the layout of the entire model has changed. The order of the elements in the list is not important. The hint parameter is used to hint what happens when the model is re-layouted.

Subclasses should update the persistent model index before issuing layoutChanged().

When the structure changes:

Issue layoutAboutToBeChanged()

Remember the QModelIndex that will change

update internal data

Call changePersistentIndex()

emit layout changed

3.3, function

1、void resetInternalData()

Called when the model is being reset after its internal data has been cleared.

2、void revert()

Lets the model know that it should discard cached information. This feature is typically used for line editing.

3、bool submit()

Lets the model know that it should commit cached information to permanent storage. This feature is typically used for line editing. Returns true if there were no errors.

4、void beginInsertColumns(const QModelIndex &parent, int first, int last)

Start a column insertion operation.

When reimplementing insertColumns() in a subclass, this function must be called before data is inserted into the model's underlying data store.

parent corresponds to the parent index where the new column is inserted, and first and last are the column numbers after the new column is inserted.

Note: This function emits the columnsAboutToBeInserted() signal, which the connected view (or proxy) must handle before inserting data. Otherwise the view may end up in an invalid state.

beginInsertColumns(parent, 4, 6);

 

 

beginInsertColumns(parent, 6, 8);

 

 

5、void beginInsertRows(const QModelIndex &parent, int first, int last)

Start a row insert operation.

When reimplementing insertRows() in a subclass, this function must be called before data is inserted into the model's underlying data store.

parent corresponds to the parent index where the new row was inserted, and first and last are the row numbers after the new row was inserted.

Note: This function emits the rowsAboutToBeInserted() signal, which the connected view (or proxy) must handle before inserting data. Otherwise, the view may end up in an invalid state.

beginInsertRows(parent, 2, 4);

 

beginInsertRows(parent, 4, 5);

 

 

6、bool beginMoveColumns(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)

Start column move operation.

When reimplementing subclasses, this method simplifies the process of moving entities in the model. Using beginMoveColumns() and endMoveColumns() is an alternative to issuing layoutAboutToBeChanged() and layoutChanged() directly with changePersistentIndex().

The sourceParent index corresponds to the parent from which the column is moved, and sourceFirst and sourceLast are the first and last column numbers of the column to be moved. The destinationParent index corresponds to the parent the columns are moved into. destinationChild is the column the column will move to. That is, the index on column sourceFirst in sourceParent becomes column destinationChild in destinationParent, and then all other columns until sourceLast.

However, when a column is moved down within the same parent (sourceParent and destinationParent are equal), the column is placed before the destinationChild index. That is, if you want to move columns 0 and 1 to become columns 1 and 2, destinationChild should be 3. In this case, the new index on source column i (between sourceFirst and sourceLast) is equal to (destinationChild-sourceLast-1+i).

Note that if sourceParent and destinationParent are the same, you must ensure that destinationChild is not within the range of sourceFirst and sourceLast + 1. You also have to make sure you don't try to move the column to one of its own children or ancestors. This method returns false if either condition is true, in which case the move operation should be aborted.

7、bool beginMoveRows(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)

Start row move operation. Similar to above.

beginMoveRows(sourceParent, 2, 4, destinationParent, 2);

 

beginMoveRows(sourceParent, 2, 4, destinationParent, 6);

 

 

beginMoveRows(parent, 2, 2, parent, 0);

 

beginMoveRows(parent, 2, 2, parent, 4);

 

 

8、void beginRemoveColumns(const QModelIndex &parent, int first, int last)

Start the column removal operation.

When reimplementing removeColumns() in a subclass, this function must be called before data is removed from the model's underlying data store.

parent corresponds to the parent index from which to drop the new column, and first and last are the column numbers of the first and last columns to be dropped.

NOTE: This function emits the columnsAboutToBeRemoved() signal, which must be handled by the connected view (or proxy) before data is removed. Otherwise, the view may end up in an invalid state.

beginRemoveColumns(parent, 4, 6);

 

9、void beginRemoveRows(const QModelIndex &parent, int first, int last)

Start the row deletion operation.

When reimplementing removeRows() in a subclass, this function must be called before data is removed from the model's underlying data store.

parent corresponds to the parent index from which to delete new rows, and first and last are the row numbers of the rows to be deleted.

Note: This function emits the rowsAboutToBeRemoved() signal, which the connected view (or proxy) must handle before data can be removed. Otherwise, the view may end up in an invalid state.

beginRemoveRows(parent, 2, 3);

 

10、void beginResetModel()

Start the model reset operation. Any views attached to this model will also be reset.

This function must be called before resetting any internal data structures in the model or proxy model.

This function signals modelAboutToBeReset().

11、QModelIndex buddy(const QModelIndex &index)

Returns the friend model index of the item represented by index.

When the user wants to edit an item, the view calls this function to check whether another item in the model should be edited. The view will then construct a delegate using the model index returned by the partner item.

12、bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)

Returns true if the model can accept drag data.

13、[invokable] bool canFetchMore(const QModelIndex &parent)

Returns true if the parent has more data available. The default implementation always returns false.

If canFetchMore() returns true, the fetchMore() function should be called.

This function can be called through the meta-object system and QML.

14、bool checkIndex(const QModelIndex &index, QAbstractItemModel::CheckIndexOptions options = CheckIndexOption::NoOption)

This function checks that index is a valid model index for this model.

A valid model index is either an invalid model index or a valid model index that satisfies all of the following conditions:

  • The index model is this
  • Indexed row is greater than or equal to zero
  • The number of rows indexed is less than the number of rows of the indexed parent
  • Indexed column is greater than or equal to zero
  • The number of columns indexed is less than the number of columns of the indexed parent

The options parameter sets the inspection options.

  • If options contains IndexIsValid, index must be a valid index.
  • If options contains DoNotUseParent, the check to call parent() is omitted. This allows this function to be called from within the parent() reimplementation (otherwise, this would cause infinite recursion and a crash).
  • If options does not contain DoNotUseParent, and contains ParentIsInvalid, an additional check is performed to see if the parent index is invalid.

15、bool clearItemData(const QModelIndex &index)

Deletes data stored in all roles at the given index. Returns true on success. If the data is successfully deleted, the dataChanged() signal should be emitted.

16 [invokable] int columnCount(const QModelIndex &parent = QModelIndex())

Returns the number of columns of children of a given parent. In most subclasses, the number of columns is independent of the parent class.

This function can be called through the meta-object system and QML.

17、QModelIndex createIndex(int row, int column, const void *ptr = nullptr)

Creates a model index for the given row and column using the internal pointer ptr.

When using QSortFilterProxyModel, its index has its own internal pointer. It is not recommended to access this internal pointer outside of the model. Use the data() function instead.

This function provides a consistent interface that model subclasses must use to create model indexes.

18 [invokable] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole)

Returns the data stored under the given role for the item referenced by the index.

If you have no value to return, return a void QVariant instead of 0.

This function can be called through the meta-object system and QML.

19、bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)

Handle drag-and-drop data.

The specified row, column, parent indicates the location of the item in the model where the operation ended. It is the responsibility of the model to complete the action in the correct position.

Call the mimeTypes() member to get a list of acceptable MIME types. This default implementation assumes the default implementation of mimeTypes(), which returns a single default MIME type. If you reimplement mimeTypes() in a custom model to return multiple MIME types, you must reimplement this function to use them.

20、void endInsertColumns()

Ends the column insert operation. When reimplementing insertColumns() in a subclass, this function must be called after data has been inserted into the model's underlying data store.

21、void endInsertRows()

Ends the row insert operation. When reimplementing insertRows() in a subclass, this function must be called after data has been inserted into the model's underlying data store.

22、void endMoveColumns()

Ends the column move operation. When subclassing, this function must be called after data has been moved in the model's underlying data store.

23、void endMoveRows()

Ends the row move operation. When subclassing, this function must be called after data has been moved in the model's underlying data store.

24、void endRemoveColumns()

End the column removal operation. When reimplementing removeColumns() in a subclass, this function must be called after data has been removed from the model's underlying data store.

25、void endRemoveRows()

Ends the row deletion operation. When reimplementing removeRows() in a subclass, this function must be called after data has been removed from the model's underlying data store.

26、void endResetModel()

Complete the model reset operation. This function must be called after resetting any internal data structures in the model or proxy model. This function signals modelReset().

27、[invokable] void fetchMore(const QModelIndex &parent)

Gets any available data for the item with the parent specified by the parent index. It needs to be reimplemented if the model is populated incrementally.

The default implementation does nothing. This function can be called through the meta-object system and QML.

28、[invokable] Qt::ItemFlags flags(const QModelIndex &index)

Returns the item flag for the given index.

The base class implementation returns a combination of flags that enable an item (ItemIsEnabled) and allow an item to be selected (ItemIsSelectable).

This function can be called through the meta-object system and QML.

29、[invokable] bool hasChildren(const QModelIndex &parent = QModelIndex())

Whether parent has children. Calling this function produces undefined behavior if the flag Qt::ItemNeverHasChildren is set for the same index.

This function can be called through the meta-object system and QML.

30、[invokable] bool hasIndex(int row, int column, const QModelIndex &parent = QModelIndex())

Returns true if the model returns a valid QModelIndex for rows and columns with parents.

This function can be called through the meta-object system and QML.

31、[invokable] QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole)

Returns data for the given role and section in the header with the specified orientation. For horizontal headings, section numbers correspond to column numbers. Likewise, for vertical headings, section numbers correspond to line numbers.

This function can be called through the meta-object system and QML.

32、[invokable] QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex())

Returns the index of the item in the model specified by the given row, column, and parent indices.

When reimplementing this function in a subclass, call createIndex() to generate model indices that other components can use to refer to items in the model.

This function can be called through the meta-object system and QML.

33、bool insertColumn(int column, const QModelIndex &parent = QModelIndex())

Inserts a single column before the given column in the children of the specified parent. Returns true if the column was successfully inserted. is actually calling insertColumns().

34、bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex())

On models that support this feature, insert the count new column into the model before the given column. The items in each new column will be children of the item represented by the parent model index.

35、bool insertRow(int row, const QModelIndex &parent = QModelIndex())

bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex())

Insert rows, similar to above.

36、QMap<int, QVariant> itemData(const QModelIndex &index)

Returns a map containing values ​​for all predefined roles in the model for the item at index.

37、[invokable] QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap))

Returns an indexed list of items in the start index column where data stored under the given role matches role. The way the search is performed is defined by flags.

The order of the results in the list may not match the order in the model.

By default, this function will perform a string-based newline comparison of all items, searching for items beginning with the search term specified by value.

The default implementation of this function searches only columns. Reimplement this function to include different search behavior.

This function can be called through the meta-object system and QML.

enum Qt::MatchFlag: This enum describes the match types that can be used when searching for items in the model.

  • Qt::MatchExactly: Performs QVariant-based matching.
  • Qt::MatchFixedString: String-based matching. String-based comparisons are case-insensitive unless the MatchCaseSensitive flag is also specified.
  • Qt::MatchContains: The search term is contained in items.
  • Qt::MatchStartsWith: Starts of search term matches.
  • Qt::MatchEndsWith: End of search term matches.
  • Qt::MatchCaseSensitive: The search is case sensitive.
  • Qt::MatchRegularExpression: Performs string-based matching using regular expressions as search terms.
  • Qt::MatchWildcard: Performs string-based matching using strings with wildcards as search terms.
  • Qt::MatchWrap: Performs a wraparound search so that when the search reaches the last item in the model, it starts again with the first item and continues until all items have been checked.
  • Qt::MatchRecursive: Searches the entire hierarchy.

38、QMimeData * mimeData(const QModelIndexList &indexes)

Returns an object containing the serialized data items corresponding to the specified list of indices. The format used to describe the encoded data is obtained from the mimeTypes() function. This default implementation uses the default MIME types returned by the default implementation of mimeTypes().

39、QStringList mimeTypes()

Returns a list of allowed MIME types. By default, built-in models and views use the internal MIME type: application/x-qabstractitemmodeldatalist.

When implementing drag and drop support in a custom model, if data is to be returned in a format other than the default internal MIME types, reimplement this function to return a list of your MIME types.

If you reimplement this function in a custom model, you must also reimplement the member functions that call it: mimeData() and dropMimeData().

40、bool moveColumn(const QModelIndex &sourceParent, int sourceColumn, const QModelIndex &destinationParent, int destinationChild)

On models that support this feature, move sourceColumn from sourceParent to destinationChild under destinationParent.

Returns true if the column was successfully moved.

41、bool moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destinationParent, int destinationChild)

On models that support this feature, moves the column starting at the given sourceColumn under the parent sourceParent to the column destinationChild under the parent destinationParent.

Returns true if the column was successfully moved.

42、bool moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild)

bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild)

Move row. Ditto.

43、void multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan)

Populates the roleDataSpan with the requested data for the given index.

44、[invokable] QModelIndex parent(const QModelIndex &index)

Returns the parent of the model item with the given index. Returns an invalid QModelIndex if the item has no parent.

This function can be called through the meta-object system and QML.

45、QModelIndexList persistentIndexList()

Returns a list of indices stored as persistent indices in the model.

46、bool removeColumn(int column, const QModelIndex &parent = QModelIndex())

Removes the given column from the children of the specified parent. Returns true if the column was dropped. Actually call removeColumns().

47、bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex())

On models that support this feature, removes from the model the count column starting with the given column under parent. Returns true if the column was successfully dropped.

48、bool removeRow(int row, const QModelIndex &parent = QModelIndex())

bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex())

Similar to above, delete rows.

49、QHash<int, QByteArray> roleNames()

Returns the model's role name.

The default role names set by Qt are:

  • Qt::DisplayRole:display
  • Qt::DecorationRole:decoration
  • Qt::EditRole:edit
  • Qt::ToolTipRole:toolTip
  • Qt::StatusTipRole:statusTip
  • Qt::WhatsThisRole:whatsThis

50 [invokable] int rowCount(const QModelIndex &parent = QModelIndex())

Returns the number of rows under the given parent.

This function can be called through the meta-object system and QML.

51、[invokable] bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole)

Sets the role data for the item at index. Returns true on success. If the data is successfully set, the dataChanged() signal should be emitted.

This function can be called through the meta-object system and QML.

52、bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole)

Set the value of the header. Returns true if the header's data has been updated.

When reimplementing this function, headerDataChanged() must be signaled explicitly.

53、bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles)

For each Qt::ItemDataRole, sets the role data of the item at index to the associated value in the role. Roles that are not in roles will not be modified.

54、[invokable] QModelIndex sibling(int row, int column, const QModelIndex &index)

Returns the row and column sibling of the item at index, or an invalid QModelIndex if there is no sibling at that position.

This function can be called through the meta-object system and QML.

55、void sort(int column, Qt::SortOrder order = Qt::AscendingOrder)

Sort the model by columns in the given order.

enum Qt::SortOrder: This enumeration describes how the items in the widget are sorted.

  • Qt::AscendingOrder: Sort in ascending order, eg start with 'AAA' and end with 'ZZZ' in Latin-1 locales
  • Qt::DescendingOrder: Sort in descending order, eg start with "ZZZ" and end with "AAA" in Latin-1 locales

56、QSize span(const QModelIndex &index)

Returns the row and column span of the item represented by the index.

57、Qt::DropActions supportedDragActions()

Returns the operations supported by the data in this model.

58、Qt::DropActions supportedDropActions()

Returns the drop operations supported by this model.

The default implementation returns Qt::CopyAction. If you want to support other operations, you need to reimplement this function. The dropMimeData() function must also be reimplemented to handle append operations.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QT embedded development, Quick module, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

QAbstractItemView

1. Description

The QAbstractItemView class is the base class for every standard view that uses QAbstractItemModel. QAbstractItemView is an abstract class and cannot be instantiated itself. It provides a standard interface for interoperating with models through the signals and slots mechanism, enabling subclasses to stay up to date with changes to the model. This class provides standard support for keyboard and mouse navigation, viewport scrolling, item editing and selection. Keyboard navigation implements this functionality:

Arrow keys change the current item and select it.

  • The Ctrl arrow key changes the current item without selecting it.
  • Shift+Arrow keys Change the current item and select it.
  • Ctr+Space Toggles the selection of the current item.
  • Tab/Backtab changes current item to next/previous item.
  • Home/End Selects the first/last item in the model.
  • Page up/Page down Scrolls up/down the displayed rows by the number of visible rows in the view.
  • Ctrl+A Selects all items in the model.

The above operation assumes that the selection mode allows the operation. For example, if the selection mode is QAbstractItemView::NoSelection, items cannot be selected.

If you inherit from QAbstractItemView and intend to update the content of the viewport, you should use viewport->update() instead of update() because all drawing operations are performed on the viewport.

Two, type members

1. enum QAbstractItemView::CursorAction: This enumeration describes different ways of navigating between items.

  • MoveUp: Move to the item above the current item.
  • MoveDown: Move to the item under the current item.
  • MoveLeft: Move to the left of the current item.
  • MoveRight: Move to the right of the current item.
  • MoveHome: Moves to the top left item.
  • MoveEnd: Moves to the bottom right item.
  • MovePageUp: Move one page above the current item.
  • MovePageDown: Move down one page below the current item.
  • MoveNext: Move to the item after the current item.
  • MovePrevious: Move to the item before the current item.

2. enum QAbstractItemView::DragDropMode: Describes various drag and drop events that the view can operate. By default, views do not support drag and drop (NoDragDrop). (Note that the model used needs to provide support for drag and drop operations)

  • NoDragDrop: Drag and drop is not supported.
  • DragOnly: The view only accepts items that support dragging itself
  • DropOnly: The view only supports drop
  • DragDrop: The view supports both drag and drop
  • InternalMove: The view only accepts move (not copy) operations from itself

3. enum QAbstractItemView::DropIndicatorPosition: This enumeration indicates the position of the drop indicator relative to the index at the current mouse position.

  • OnItem: item will be dragged and dropped on the index
  • AboveItem: the item will be dragged and dropped above the index
  • BelowItem: item will be dragged and dropped below the index
  • OnViewport: The item will be dragged and dropped on a viewport area that has no items

4. enum QAbstractItemView::EditTrigger: This enumeration describes the operation that will start item editing.

  • NoEditTriggers: Cannot edit.
  • CurrentChanged: Start editing whenever the current item changes.
  • DoubleClicked: Editing starts when an item is double-clicked.
  • SelectedClicked: Editing starts when a selected item is clicked.
  • EditKeyPressed: Editing starts when the platform edit key is pressed on the item.
  • AnyKeyPressed: Start editing when any key is pressed on the item.
  • AllEditTriggers: All of the above actions start editing.

5、enum QAbstractItemView::ScrollHint

  • EnsureVisible: Scroll to ensure the item is visible
  • PositionAtTop: scroll to position the item at the top of the viewport
  • PositionAtBottom: scroll to position the item at the bottom of the viewport
  • PositionAtCenter: Scroll to position the item at the center of the viewport

6. enum QAbstractItemView::ScrollMode: Describes the behavior of the scroll bar. When scroll mode is set to ScrollPerPixel, single step size will be adjusted automatically unless explicitly set with setSingleStep(). Autoscale can be restored by setting the single step size to -1.

  • ScrollPerItem: The view will scroll one item at a time.
  • ScrollPerPixel: The view will scroll the content one pixel at a time.

7、enum QAbstractItemView::SelectionBehavior:

SelectItems:选择单个项目
SelectRows:只选择行
SelectColumns:只选择列

8. enum QAbstractItemView::SelectionMode: This enumeration indicates how the view responds to user selection. The most commonly used modes are SingleSelection and ExtendedSelection.

SingleSelection: Single selection. Pressing the Ctrl key while clicking a selected item deselects the item

ContiguousSelection: Press radio. But if you press the Shift key while clicking an item, all items between the current item and the clicked item will be checked or unchecked, depending on the state of the clicked item

ExtendedSelection: Press radio. But if you hold down the Ctrl key while clicking on an item, the clicked item will be toggled, leaving all other items unchanged. If you hold down the Shift key while clicking an item, all items between the current item and the clicked item are checked or unchecked, depending on the state of the clicked item. Multiple items can be selected by dragging the mouse over them

  • MultiSelection: multiple selection
  • NoSelection: Item cannot be selected

9. enum QAbstractItemView::State: Describes the different states that the view can be in. Usually only used when reimplementing views.

  • NoState: default state
  • DraggingState: The user is dragging the item
  • DragSelectingState: The user is selecting an item
  • EditingState: The user is editing an item in the widget editor
  • ExpandingState; the user is opening a branch of the project
  • CollapsingState: The user is closing a branch of the project
  • AnimatingState: The item view is animating

Three, attribute members

1、alternatingRowColors : bool

This property holds whether the background is drawn with alternating colors. The default is false.

If this property is true, the item background will be painted using QPalette::Base and QPalette::AlternateBase; otherwise the background will be painted using the QPalette::Base color.

2、autoScroll : bool

This property holds whether autoscrolling on drag move events is enabled. The default is true.

If this property is set to true, the QAbstractItemView automatically scrolls the view's contents if the user drags within 16 pixels of the edge of the viewport. If the current item changes, the view will automatically scroll to ensure the current item is fully visible.

This property is only valid if the viewport accepts drops.

3、autoScrollMargin : int

This property holds the size of the region when autoscroll is triggered. The default is 16 pixels.

4、defaultDropAction : Qt::DropAction

This property holds the drop action that will be used by default in drag().

If this property is not set, the put action is CopyAction if the supported action supports CopyAction.

enum Qt::DropAction:

  • Qt::CopyAction: Copy data to target
  • Qt::MoveAction: Move data from source to target
  • Qt::LinkAction: create a link from source to target
  • Qt::ActionMask
  • Qt::IgnoreAction: Do nothing with the data
  • Qt::TargetMoveAction: On Windows, this value is used when ownership of the dragged data should be taken over by the target application, ie the source application should not delete the data. On X11 this value is used for movement. TargetMoveAction is not used on Mac.

5、dragDropMode : DragDropMode

This property holds the drag mode of the view.

6、dragDropOverwriteMode : bool

This property holds the drag and drop behavior of the view.

If true, checked data will overwrite existing item data when dropped, and moving data will clear the item.

If false, when data is deleted, the selected data will be inserted as a new item. Items are also deleted when data is moved.

7、dragEnabled : bool

This property holds whether the view supports dragging its own items.

8、editTriggers : EditTriggers

This property holds which actions will initiate item editing.

This property is a selection of flags defined by EditTrigger, combined using the OR operator.

9、horizontalScrollMode : ScrollMode

This property controls how the view scrolls its content horizontally. Scrolling can be done by pixel or by item.

Its default value comes from the style hinted via QStyle::SH_ItemView_ScrollMode (the default vertical and horizontal scrolling mode specified by the style. Can be overridden with QAbstractItemView::setVerticalScrollMode() and QAbstractItemView::setHorizontalScrollMode() ).

10、iconSize : QSize

This property holds the size of the item icon.

Setting this property while the view is visible will cause the item to be laid out again.

11、selectionBehavior : SelectionBehavior

This property holds the selection behavior used by the view.

12、selectionMode : SelectionMode

This property holds which selection mode the view is operating in.

Whether one or more items can be selected, and in multi-item selection, whether the selection must be a contiguous range of items.

13、showDropIndicator : bool

This property holds whether to display the drop indicator when dragging and dropping items.

14、tabKeyNavigation : bool

This property holds whether item navigation with tabs and backtabs is enabled.

15、textElideMode : Qt::TextElideMode

This property holds the position of "..." in the omitted text.

The default for all item views is Qt::ElideRight.

enum Qt::TextElideMode: This enumeration specifies where the ellipsis should appear when displaying unsuitable text.

  • Qt::ElideLeft: the beginning of the text
  • Qt::ElideRight: end of text
  • Qt::ElideMiddle: the middle of the text
  • Qt::ElideNone: ellipsis should not appear in the text

16、verticalScrollMode : ScrollMode

How the view scrolls its content vertically. Similar to item 9.

4. Member functions

4.1. Signal

1、void activated(const QModelIndex &index)

This signal is emitted when the user activates the item specified by index.

2、void clicked(const QModelIndex &index)

This signal is emitted when the left mouse button is clicked. The item clicked by the mouse is specified by index. This signal is only emitted when the index is valid.

3、void doubleClicked(const QModelIndex &index)

This signal is emitted when the mouse button is double-clicked. The item that the mouse double-clicks on is specified by index. This signal is only emitted when the index is valid.

4、void entered(const QModelIndex &index)

This signal is emitted when the mouse cursor enters the item specified by index. Mouse tracking needs to be enabled to use this feature.

5、void pressed(const QModelIndex &index)

This signal is emitted when a mouse button is pressed. The item the mouse pressed is specified by index. This signal is only emitted when the index is valid.

Use the QGuiApplication::mouseButtons() function to get the state of the mouse buttons.

6、void viewportEntered()

This signal is emitted when the mouse cursor enters the viewport. Mouse tracking needs to be enabled to use this feature.

4.2, function

1、void clearSelection()

Deselects all selected items. The current index will not change.

2、void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint)

Closes the given editor, then releases it. The hint is used to specify how the view should respond to the end of an editing operation. (for delegation)

3、void commitData(QWidget *editor)

Commits the data in the editor to the model. (for delegation)

4、void currentChanged(const QModelIndex ¤t, const QModelIndex &previous)

This slot is called when the current index changes.

5、void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &roles = QList<int>())

This slot is called when an item in the model with the given role changes. The items that change are the ones from topLeft to bottomRight.

Note: dataChanged() does not support Qt::ToolTipRole.

6、void edit(const QModelIndex &index)

If editable, starts editing the item corresponding to the given index.

7、void editorDestroyed(QObject *editor)

This function is called when the given editor is destroyed. (for delegation)

8、void reset()

Reset the internal state of the view.

9、void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)

This slot is called when a row is about to be deleted. The deleted lines are those from start to end under the parent item.

10、void rowsInserted(const QModelIndex &parent, int start, int end)

Similarly, delete columns.

11、void scrollToBottom() / void scrollToTop()

Scroll view to bottom/top.

12、void selectAll()

Selects all items in the view.

13、void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)

This slot is called when the selection is changed. The previous selection (possibly empty) is specified by deselected and the new selection is specified by selected.

14、void setCurrentIndex(const QModelIndex &index)

Sets the current item to the item at index.

The item is also selected unless the current selection mode is NoSelection.

To set the item as the current item without selecting it, call:

selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);

15、void setRootIndex(const QModelIndex &index)

Set up the root project.

16、void update(const QModelIndex &index)

Update the area occupied by the given index.

17、void updateGeometries()

Update the geometry of the view's subwidgets.

18、void closePersistentEditor(const QModelIndex &index)

Closes the persistent editor for the item at the given index.

19、QModelIndex currentIndex()

Returns the model index of the current project.

20、void dragEnterEvent(QDragEnterEvent *event)

void dragLeaveEvent(QDragLeaveEvent *event)
void dragMoveEvent(QDragMoveEvent *event)
void dropEvent(QDropEvent *event)

Drag related events. Qt drag and drop.

21、int horizontalOffset() / verticalOffset()

Returns the horizontal/vertical offset of the view.

22、QModelIndex indexAt(const QPoint &point)

Returns the model index of the item at the viewport coordinate point.

23、QWidget * indexWidget(const QModelIndex &index)

Returns the widget for the item at the given index.

24、void initViewItemOption(QStyleOptionViewItem *option)

Initializes the options structure with the view's palette, font, state, alignment, etc.

25、bool isIndexHidden(const QModelIndex &index)

Returns true if the item referenced by the given index is hidden from view.

Hiding is a view-specific feature. For example, in a TableView, you can mark a column as hidden or a row in a TreeView.

26、bool isPersistentEditorOpen(const QModelIndex &index)

Returns whether a persistent editor is opened for the item at index index.

27、QAbstractItemDelegate * itemDelegate() / void setItemDelegate(QAbstractItemDelegate *delegate)

QAbstractItemView does not take ownership of the delegate.

Warning: You should not share the same delegate instance between views. Doing so can result in incorrect or unintuitive editing behavior, since every view connected to a given delegate may receive the closeEditor() signal and attempt to access, modify, or close a closed editor.

28、QAbstractItemDelegate * itemDelegateForColumn(int column)

void setItemDelegateForColumn(int column, QAbstractItemDelegate *delegate)

Sets the given item delegate used by this view and model for the given column.

All items on the column will be drawn and managed by a delegate instead of using the default delegate (i.e. itemDelegate()).

29、void setItemDelegateForRow(int row, QAbstractItemDelegate *delegate)

QAbstractItemDelegate * itemDelegateForRow(int row)

Similar to above, OK.

30、QAbstractItemDelegate * itemDelegateForIndex(const QModelIndex &index)

Returns the item delegate used by this view and model for the given index.

31、void keyboardSearch(const QString &search)

Move to and select the item that best matches the string.

32、void openPersistentEditor(const QModelIndex &index)

Open a persistent editor on the item at the given index. If no editor exists, the delegate will create a new one.

33、QModelIndex rootIndex()

Returns the model index of the root item of the model. The root item is the parent of the view's top-level item. Root may not be valid.

34、void scheduleDelayedItemsLayout()

Arranges the layout of the items in the view to be executed when event processing begins.

Even if scheduleDelayedItemsLayout() is called multiple times before handling the event, the view will only be laid out once.

35、void scrollTo(const QModelIndex &index, QAbstractItemView::ScrollHint hint = EnsureVisible)

If necessary, scroll the view to ensure the item at the index is visible. The view will attempt to position the item based on the given hint.

36、QModelIndexList selectedIndexes()

This convenience function returns a list of all selected and non-hidden item indices in the view. The list contains no duplicates and is not sorted.

37、QItemSelectionModel::SelectionFlags selectionCommand(const QModelIndex &index, const QEvent *event = nullptr)

Returns the SelectionFlags to use when updating the selection to include the specified index. event is a user input event, such as a mouse or keyboard event.

38、QItemSelectionModel * selectionModel()

Returns the currently selected model.

39、void setIndexWidget(const QModelIndex &index, QWidget *widget)

Sets the given widget on the item at the given index, passing ownership of the widget to the viewport.

The autoFillBackground property of a given widget must be set to true, otherwise the widget's background will be transparent, showing both the model data and the item at the given index.

If index widget A is replaced by index widget B, index widget A will be removed.

This function should only be used to display static content within the visible area corresponding to the data item. If you want to display custom dynamic content or implement a custom editor widget, you should instead delegate (QStyledItemDelegate).

40、void setModel(QAbstractItemModel *model)

Sets the model of the view to render.

This function will create and set a new selection model, replacing any model previously set with setSelectionModel(). However, the old selection model will not be removed as it may be shared between multiple views. If the old selection model is no longer needed, it should be deleted manually.

QItemSelectionModel *m = view->selectionModel();
view->setModel(new model);
delete m;

If neither the old model nor the old selection model has a parent, or if their parent is a long-lived object, it is best to delete them explicitly by calling their deleteLater() function.

A view does not take ownership of a model unless it is the model's parent, since a model may be shared among many different views.

41、void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags flags)

Applies the selection flag to items in or touching the rectangle rect.

42、void setSelectionModel(QItemSelectionModel *selectionModel)

Set the selection model.

43、int sizeHintForColumn(int column) / int sizeHintForRow(int row)

Returns the width/height size hint for the specified column. (Maximum height/width of the item) (To control the height of the row, you must reimplement the QAbstractItemDelegate::sizeHint() function.)

44、QSize sizeHintForIndex(const QModelIndex &index)

Returns a size hint for the item with the specified index.

45、void startDrag(Qt::DropActions supportedActions)

Start dragging by calling drag->exec() with the given supportedActions.

46、QRect visualRect(const QModelIndex &index)

Returns the rectangle on the viewport that the item at index occupies.

47、QRegion visualRegionForSelection(const QItemSelection &selection) const

Returns the region from the viewport of the items in the given selection.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QT embedded development, Quick module, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Original link: https://blog.csdn.net/kenfan1647/article/details/119277723

Guess you like

Origin blog.csdn.net/hw5230/article/details/131987274