QAbstractItemModel 类

QAbstractItemModel 类为项模型类提供了抽象接口。更多……

头文件: #include <QAbstractItemModel>
CMake: find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
继承: QObject
派生:

QAbstractItemModelReplicaQAbstractListModelQAbstractProxyModelQAbstractTableModelQConcatenateTablesProxyModelQFileSystemModelQHelpContentModelQStandardItemModel

公共成员类型

enum class CheckIndexOption { NoOption, IndexIsValid, DoNotUseParent, ParentIsInvalid }
flags CheckIndexOptions
enum LayoutChangeHint { NoLayoutChangeHint, VerticalSortHint, HorizontalSortHint }

公共成员函数

QAbstractItemModel(QObject *parent = nullptr)
virtual ~QAbstractItemModel()
virtual QModelIndex buddy(const QModelIndex &index) const
virtual bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
virtual bool canFetchMore(const QModelIndex &parent) const
bool checkIndex(const QModelIndex &index, QAbstractItemModel::CheckIndexOptions options = CheckIndexOption::NoOption) const
virtual bool clearItemData(const QModelIndex &index)
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const = 0
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const = 0
virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
virtual void fetchMore(const QModelIndex &parent)
virtual Qt::ItemFlags flags(const QModelIndex &index) const
virtual bool hasChildren(const QModelIndex &parent = QModelIndex()) const
bool hasIndex(int row, int column, const QModelIndex &parent = QModelIndex()) const
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const = 0
bool insertColumn(int column, const QModelIndex &parent = QModelIndex())
virtual bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex())
bool insertRow(int row, const QModelIndex &parent = QModelIndex())
virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex())
virtual QMap<int, QVariant> itemData(const QModelIndex &index) const
virtual QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const
virtual QMimeData *mimeData(const QModelIndexList &indexes) const
virtual QStringList mimeTypes() const
bool moveColumn(const QModelIndex &sourceParent, int sourceColumn, const QModelIndex &destinationParent, int destinationChild)
virtual bool moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destinationParent, int destinationChild)
bool moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild)
virtual bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild)
virtual void multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const
virtual QModelIndex parent(const QModelIndex &index) const = 0
bool removeColumn(int column, const QModelIndex &parent = QModelIndex())
virtual bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex())
bool removeRow(int row, const QModelIndex &parent = QModelIndex())
virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex())
virtual QHash<int, QByteArray> roleNames() const
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const = 0
virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole)
virtual bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole)
virtual bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles)
virtual QModelIndex sibling(int row, int column, const QModelIndex &index) const
virtual void sort(int column, Qt::SortOrder order = Qt::AscendingOrder)
virtual QSize span(const QModelIndex &index) const
virtual Qt::DropActions supportedDragActions() const
virtual Qt::DropActions supportedDropActions() const

公共槽函数

virtual void revert()
virtual bool submit()

信号

void columnsAboutToBeInserted(const QModelIndex &parent, int first, int last)
void columnsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationColumn)
void columnsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
void columnsInserted(const QModelIndex &parent, int first, int last)
void columnsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int column)
void columnsRemoved(const QModelIndex &parent, int first, int last)
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &roles = QList<int>())
void headerDataChanged(Qt::Orientation orientation, int first, int last)
void layoutAboutToBeChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)
void layoutChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)
void modelAboutToBeReset()
void modelReset()
void rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
void rowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
void rowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
void rowsInserted(const QModelIndex &parent, int first, int last)
void rowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row)
void rowsRemoved(const QModelIndex &parent, int first, int last)

受保护的函数

void beginInsertColumns(const QModelIndex &parent, int first, int last)
void beginInsertRows(const QModelIndex &parent, int first, int last)
bool beginMoveColumns(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)
bool beginMoveRows(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)
void beginRemoveColumns(const QModelIndex &parent, int first, int last)
void beginRemoveRows(const QModelIndex &parent, int first, int last)
void beginResetModel()
void changePersistentIndex(const QModelIndex &from, const QModelIndex &to)
void changePersistentIndexList(const QModelIndexList &from, const QModelIndexList &to)
QModelIndex createIndex(int row, int column, const void *ptr = nullptr) const
QModelIndex createIndex(int row, int column, quintptr id) const
void endInsertColumns()
void endInsertRows()
void endMoveColumns()
void endMoveRows()
void endRemoveColumns()
void endRemoveRows()
void endResetModel()
QModelIndexList persistentIndexList() const

受保护的槽函数

virtual void resetInternalData()

详细描述

QAbstractItemModel 类定义了项模型与模型/视图体系结构中的其他组件进行交互操作时必须使用的标准接口。应该子类化该类创建新的模型,而不是直接实例化使用。

QAbstractItemModel 类是 模型/视图类 中的一个,也是 模型/视图框架的一部分。它可以用作 QML 中的项视图元素或 Qt Widgets 模块中的项视图类的底层数据模型。

如果需要一个模型来使用项视图,比如 QML 的 List View 元素或者 C++ widgets 的 QListView 或者 QTableView,应该考虑子类化 QAbstractListModel 或者 QAbstractTableModel 而不是使用该类。

底层数据模型作为表的层次结构暴露给视图和委托。如果不使用层次结构,那么模型就是一个简单的具有行和列的表。每个项都有一个由 QModelIndex 指定的惟一索引。

每个数据项都可以通过包含一个关联的模型索引的模型进行访问。该索引可以通过 index() 函数获得。每个索引可能有一个 sibling() 索引;子项有一个 parent() 索引。

每个项目都有许多与之关联的数据元素,可以通过为模型的 data() 函数指定一个角色(请参阅 Qt::ItemDataRole)来检索它们。可以使用 itemData() 函数同时获取所有可用角色的数据。

使用特定的 Qt::ItemDataRole设置每个角色的数据。可以使用 setData()单独设置各个角色的数据,也可以使用 setItemData() 设置所有角色的数据。

可以使用 flags() 查询项(请参阅 Qt::ItemFlag),以查看是否可以通过其他方式选择,拖动或操纵它们。

如果项具有子对象,则 hasChildren() 为相应的索引返回 true

该模型在层次结构的每个级别都有一个 rowCount() 和 columnCount()。可以使用 insertRows(),insertColumns(),removeRows() 和 removeColumns() 插入和删除行和列。

模型发出信号以指示变化。例如,只要模型可用的数据项发生更改,就会发出 dataChanged()。对模型提供的标题的更改将将发射 headerDataChanged() 信号。如果底层数据的结构发生了变化,则模型可以发出 layoutChanged() 来向任何附加的视图指示它们应该重新显示所显示的任何项,并需要考虑到新的结构。

可以使用 match() 函数在模型中搜索可用的项以查找特定数据。

要对模型进行排序,可以使用 sort()。

子类化

注意:模型子类化参考 中有一些关于模型子类化的通用指南。

子类化 QAbstractItemModel 时,至少必须实现 index(),parent(),rowCount(),columnCount() 和 data()。这些函数在所有的只读模型中使用,同样也构成了可编辑模型的基础。

还可以为模型重新实现 hasChildren() 来提供特殊的行为,而不是重新实现成本很高的 rowCount()。这使得模型可以限制视图请求的数据量,并且可以作为实现模型数据的惰性填充的一种方式。

要在模型中启用编辑,还必须实现 setData() 和重新实现 flags() 以确保返回 ItemIsEditable。还可以重新实现 headerData() 和 setHeaderData() 来控制呈现模型标题的方式。

当分别重新实现setData() 和 setHeaderData() 函数时,必须显式发射 dataChanged() 和 headerDataChanged() 信号。

定制模型需要创建模型索引以供其他组件使用。为此,请使用适当的行号和列号以及相应的标识符调用 createIndex(),并将其作为指针或整数值。这些值的组合对于每个项都必须是唯一的。定制模型通常在其他重新实现的函数中使用这些唯一标识符,以检索项数据并访问有关该项的父项和子项的信息。有关唯一标识符的更多信息,请参见 简单树模型 示例。

不必支持 Qt::ItemDataRole中定义的每个角色。根据模型中包含的数据类型,可能只有实现 data() 函数以返回一些更常见角色的有效信息才有用。大多数模型至少为 Qt::DisplayRole提供项数据的文本表示,行为良好的模型也应为 Qt::ToolTipRoleQt::WhatsThisRole提供有效信息。支持这些角色可使模型与标准 Qt 视图一起使用。但是,对于某些处理高度专业化数据的模型,仅为用户定义的角色提供数据可能是合适的。

提供可调整数据结构大小的接口的模型可以提供 insertRows(),removeRows(),insertColumns() 和 removeColumns()的实现。在实现这些函数时,重要的是要在模型尺寸大小发生 之前之后 将有关模型尺寸的更改通知所有连接的视图:

这些函数发出的 私有 信号使附加组件有机会在任何数据变得不可用之前采取行动。使用这些 begin 和 end 函数封装插入和删除操作还使模型能够正确地管理 持久模型索引 correctly。如果希望正确处理选择,则必须确保调用了这些函数。 果插入或移除带有子项的项,则不需要为子项调用这些函数。换句话说,父项将管理其子项。

要创建增量填充的模型,可以重新实现 fetchMore() 和 canFetchMore()。如果 fetchMore() 的重新实现向模型中添加了行,则必须调用 beginInsertRows()endInsertRows()

参见 模型类模型子类化参考QModelIndexQAbstractItemView在项视图中使用拖放简单DOM模型示例简单树模型示例可编辑树模型示例Fetch More 示例

成员类型文档

[since 5.11] enum class QAbstractItemModel::CheckIndexOption
flags QAbstractItemModel::CheckIndexOptions

这个枚举可以用来控制 QAbstractItemModel::checkIndex() 执行的检查。

ConstantValueDescription
QAbstractItemModel::CheckIndexOption::NoOption0x0000没有指定检查选项。
QAbstractItemModel::CheckIndexOption::IndexIsValid0x0001传递给 QAbstractItemModel::checkIndex() 的模型索引被检查为有效的模型索引。
QAbstractItemModel::CheckIndexOption::DoNotUseParent0x0002不执行任何涉及到传递给 QAbstractItemModel::checkIndex() 的父索引的使用的检查。
QAbstractItemModel::CheckIndexOption::ParentIsInvalid0x0004传递给 QAbstractItemModel::checkIndex() 的模型索引的父索引被检查为无效的模型索引。如果同时指定了此选项和 DoNotUseParent,则忽略此选项。

该枚举是在 Qt 5.11 中引入或修改的。

CheckIndexOptions 类型是一个 QFlags<CheckIndexOption> 的类型定义。它存储一个或组合的 CheckIndexOption 值。

enum QAbstractItemModel::LayoutChangeHint

这个枚举描述了模型改变布局的方式。

ConstantValueDescription
QAbstractItemModel::NoLayoutChangeHint0没有任何提示。
QAbstractItemModel::VerticalSortHint1正在对行进行排序。
QAbstractItemModel::HorizontalSortHint2正在对列进行排序。

注意,VerticalSortHint 和 HorizontalSortHint 表示项在同一父级中移动,而不是移动到模型中的不同父级,也没有过滤掉或过滤进来。

成员函数文档

QAbstractItemModel::QAbstractItemModel(QObject *parent = nullptr)

构造指定父类对象 parent 的抽象项模型。

[private signal] void QAbstractItemModel::columnsAboutToBeInserted(const QModelIndex &parent, int first, int last)

在将列插入模型之前就发射此信号。新项将位于给定父项 parent 下的首 firstlast 之间。

注意:连接到这个信号的组件使用它来适应模型尺寸的变化。它只能由 QAbstractItemModel 的实现发射,不能在子类代码中显式发射。

注意:这是一个私有信号。它可以用于信号连接,但不能由用户发射。

参见 insertColumns() 和 beginInsertColumns()。

[private signal] void QAbstractItemModel::columnsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationColumn)

模型中的列被移动之前发射该信号。将要移动的项是在给定 sourceParent 下在 sourceStartsourceEnd 之间(包括首尾)的项。它们将从 destinationParent 列开始移动到 destinationColumn

注意: 连接到该信号的组件使用它来适应模型尺寸的变化。它只能由 QAbstractItemModel 实现发射,不能在子类代码中显式发射。

注意:这是一个私有信号。仅用于信号连接,而不能由用户发射。

参见 beginMoveRows()。

[private signal] void QAbstractItemModel::columnsAboutToBeRemoved(const QModelIndex &parent, int first, int last)

模型中的列被移除之前发射该信号。将要移除的项是在给定 parent 下在 firstlast 之间(包括首尾)的项。

注意:连接到该信号的组件使用它来适应模型尺寸的变化。它只能由 QAbstractItemModel 实现发射,不能在子类代码中显式发射。

注意:这是一个私有信号。仅用于信号连接,而不能由用户发射。

参见 removeColumns() 和 beginRemoveColumns()。

[private signal] void QAbstractItemModel::columnsInserted(const QModelIndex &parent, int first, int last)

将列插入到模型之后发射该信号。新的项是在给定 parent 下在 firstlast 之间(包括首尾)的项。

注意:连接到该信号的组件使用它来适应模型尺寸的变化。它只能由 QAbstractItemModel实现发射,不能在子类代码中显式发射。

注意:这是一个私有信号。仅用于信号连接,而不能由用户发射。

参见 insertColumns() 和 beginInsertColumns()。

[private signal] void QAbstractItemModel::columnsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int column)

模型中的列被移动之后发射该信号。新的项是在给定 parent 下在 startend 之间(包括首尾)的项。它们将从 column 列开始移动到 destination

注意: 连接到该信号的组件使用它来适应模型尺寸的变化。它只能由 QAbstractItemModel 实现发射,不能在子类代码中显式发射。

注意:这是一个私有信号。仅用于信号连接,而不能由用户发射。

参见 beginMoveRows()。

[private signal] void QAbstractItemModel::columnsRemoved(const QModelIndex &parent, int first, int last)

模型中的列被移除之后发射该信号。移除的项是在给定 parent 下在 firstlast 之间(包括首尾)的项。

注意:连接到该信号的组件使用它来适应模型尺寸的变化。它只能由 QAbstractItemModel 实现发射,不能在子类代码中显式发射。

注意:这是一个私有信号。仅用于信号连接,而不能由用户发射。

参见 removeColumns() 和 beginRemoveColumns()。

[signal] void QAbstractItemModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &roles = QList<int>())

现有的项的数据发生改变时发射该信号。

如果项是同一父项,则受影响的项是在 topLeftbottomRight(包含)之间的项目。如果项没有相同的父项,则行为是不确定的。

当重新实现 setData() 函数时,必须显示地发射该信号。

可选的 roles 参数可用于指定实际修改了哪些数据角色。Roles 参数中的向量为空,表示应将所有角色视为已修改。角色参数中元素的顺序没有任何关联。

参见 headerDataChanged(),setData() 和 layoutChanged()。

[signal] void QAbstractItemModel::headerDataChanged(Qt::Orientation orientation, int first, int last)

当标题改变时发射该信号。orientation indicates whether the horizontal or vertical header has changed. The sections in the header from the first to the last need to be updated.

When reimplementing the setHeaderData() function, this signal must be emitted explicitly.

If you are changing the number of columns or rows you do not need to emit this signal, but use the begin/end functions (refer to the section on subclassing in the QAbstractItemModel class description for details).

See also headerData(), setHeaderData(), and dataChanged().

[signal, since 5.0] void QAbstractItemModel::layoutAboutToBeChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)

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

Subclasses should update any persistent model indexes after emitting layoutAboutToBeChanged().

The optional parents parameter is used to give a more specific notification about what parts of the layout of the model are changing. An empty list indicates a change to the layout of the entire model. The order of elements in the parents list is not significant. The optional hint parameter is used to give a hint about what is happening while the model is relayouting.

This function was introduced in Qt 5.0.

See also layoutChanged() and changePersistentIndex().

[signal, since 5.0] void QAbstractItemModel::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 has changed; for example, when the model has been sorted. When this signal is received by a view, it should update the layout of items to reflect this change.

When subclassing QAbstractItemModel or QAbstractProxyModel, ensure that you emit layoutAboutToBeChanged() before changing the order of items or altering the structure of the data you expose to views, and emit layoutChanged() after changing the layout.

The optional parents parameter is used to give a more specific notification about what parts of the layout of the model are changing. An empty list indicates a change to the layout of the entire model. The order of elements in the parents list is not significant. The optional hint parameter is used to give a hint about what is happening while the model is relayouting.

Subclasses should update any persistent model indexes before emitting layoutChanged(). In other words, when the structure changes:

This function was introduced in Qt 5.0.

See also layoutAboutToBeChanged(), dataChanged(), headerDataChanged(), modelReset(), and changePersistentIndex().

[private signal] void QAbstractItemModel::modelAboutToBeReset()

This signal is emitted when beginResetModel() is called, before the model's internal state (e.g. persistent model indexes) has been invalidated.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also beginResetModel() and modelReset().

[private signal] void QAbstractItemModel::modelReset()

This signal is emitted when endResetModel() is called, after the model's internal state (e.g. persistent model indexes) has been invalidated.

Note that if a model is reset it should be considered that all information previously retrieved from it is invalid. This includes but is not limited to the rowCount() and columnCount(), flags(), data retrieved through data(), and roleNames().

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also endResetModel() and modelAboutToBeReset().

[virtual protected slot] void QAbstractItemModel::resetInternalData()

This slot is called just after the internal data of a model is cleared while it is being reset.

This slot is provided the convenience of subclasses of concrete proxy models, such as subclasses of QSortFilterProxyModel which maintain extra data.

 class CustomDataProxy : public QSortFilterProxyModel
 {
     Q_OBJECT
 public:
     CustomDataProxy(QObject *parent)
       : QSortFilterProxyModel(parent)
     {
     }

     ...

     QVariant data(const QModelIndex &index, int role) override
     {
         if (role != Qt::BackgroundRole)
             return QSortFilterProxyModel::data(index, role);

         if (m_customData.contains(index.row()))
             return m_customData.value(index.row());
         return QSortFilterProxyModel::data(index, role);
     }

 private slots:
     void resetInternalData()
     {
         m_customData.clear();
     }

 private:
   QHash<int, QVariant> m_customData;
 };

Note: Due to a mistake, this slot is missing in Qt 5.0.

See also modelAboutToBeReset() and modelReset().

[virtual slot] void QAbstractItemModel::revert()

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

See also submit().

[private signal] void QAbstractItemModel::rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)

This signal is emitted just before rows are inserted into the model. The new items will be positioned between start and end inclusive, under the given parent item.

Note: Components connected to this signal use it to adapt to changes in the model's dimensions. It can only be emitted by the QAbstractItemModel implementation, and cannot be explicitly emitted in subclass code.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also insertRows() and beginInsertRows().

[private signal] void QAbstractItemModel::rowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)

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

Note: Components connected to this signal use it to adapt to changes in the model's dimensions. It can only be emitted by the QAbstractItemModel implementation, and cannot be explicitly emitted in subclass code.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also beginMoveRows().

[private signal] void QAbstractItemModel::rowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)

This signal is emitted just before rows are removed from the model. The items that will be removed are those between first and last inclusive, under the given parent item.

Note: Components connected to this signal use it to adapt to changes in the model's dimensions. It can only be emitted by the QAbstractItemModel implementation, and cannot be explicitly emitted in subclass code.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also removeRows() and beginRemoveRows().

[private signal] void QAbstractItemModel::rowsInserted(const QModelIndex &parent, int first, int last)

This signal is emitted after rows have been inserted into the model. The new items are those between first and last inclusive, under the given parent item.

Note: Components connected to this signal use it to adapt to changes in the model's dimensions. It can only be emitted by the QAbstractItemModel implementation, and cannot be explicitly emitted in subclass code.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also insertRows() and beginInsertRows().

[private signal] void QAbstractItemModel::rowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row)

This signal is emitted after rows have been moved within the model. The items between start and end inclusive, under the given parent item have been moved to destination starting at the row row.

Note: Components connected to this signal use it to adapt to changes in the model's dimensions. It can only be emitted by the QAbstractItemModel implementation, and cannot be explicitly emitted in subclass code.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also beginMoveRows().

[private signal] void QAbstractItemModel::rowsRemoved(const QModelIndex &parent, int first, int last)

This signal is emitted after rows have been removed from the model. The removed items are those between first and last inclusive, under the given parent item.

Note: Components connected to this signal use it to adapt to changes in the model's dimensions. It can only be emitted by the QAbstractItemModel implementation, and cannot be explicitly emitted in subclass code.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also removeRows() and beginRemoveRows().

[virtual slot] bool QAbstractItemModel::submit()

Lets the model know that it should submit cached information to permanent storage. This function is typically used for row editing.

Returns true if there is no error; otherwise returns false.

See also revert().

[virtual] QAbstractItemModel::~QAbstractItemModel()

Destroys the abstract item model.

[protected] void QAbstractItemModel::beginInsertColumns(const QModelIndex &parent, int first, int last)

Begins a column insertion operation.

When reimplementing insertColumns() in a subclass, you must call this function before inserting data into the model's underlying data store.

The parent index corresponds to the parent into which the new columns are inserted; first and last are the column numbers of the new columns will have after they have been inserted.

Inserting columnsSpecify the first and last column numbers for the span of columns you want to insert into an item in a model.

For example, as shown in the diagram, we insert three columns before column 4, so first is 4 and last is 6:

 beginInsertColumns(parent, 4, 6);

This inserts the three new columns as columns 4, 5, and 6.

Appending columnsTo append columns, insert them after the last column.

For example, as shown in the diagram, we append three columns to a collection of six existing columns (ending in column 5), so first is 6 and last is 8:

 beginInsertColumns(parent, 6, 8);

This appends the two new columns as columns 6, 7, and 8.

Note: This function emits the columnsAboutToBeInserted() signal which connected views (or proxies) must handle before the data is inserted. Otherwise, the views may end up in an invalid state.

See also endInsertColumns().

[protected] void QAbstractItemModel::beginInsertRows(const QModelIndex &parent, int first, int last)

Begins a row insertion operation.

When reimplementing insertRows() in a subclass, you must call this function before inserting data into the model's underlying data store.

The parent index corresponds to the parent into which the new rows are inserted; first and last are the row numbers that the new rows will have after they have been inserted.

Inserting rowsSpecify the first and last row numbers for the span of rows you want to insert into an item in a model.

For example, as shown in the diagram, we insert three rows before row 2, so first is 2 and last is 4:

 beginInsertRows(parent, 2, 4);

This inserts the three new rows as rows 2, 3, and 4.

Appending rowsTo append rows, insert them after the last row.

For example, as shown in the diagram, we append two rows to a collection of 4 existing rows (ending in row 3), so first is 4 and last is 5:

 beginInsertRows(parent, 4, 5);

This appends the two new rows as rows 4 and 5.

Note: This function emits the rowsAboutToBeInserted() signal which connected views (or proxies) must handle before the data is inserted. Otherwise, the views may end up in an invalid state.

See also endInsertRows().

[protected] bool QAbstractItemModel::beginMoveColumns(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)

Begins a column move operation.

When reimplementing a subclass, this method simplifies moving entities in your model. This method is responsible for moving persistent indexes in the model, which you would otherwise be required to do yourself. Using beginMoveColumns and endMoveColumns is an alternative to emitting layoutAboutToBeChanged and layoutChanged directly along with changePersistentIndex.

The sourceParent index corresponds to the parent from which the columns are moved; sourceFirst and sourceLast are the first and last column numbers of the columns to be moved. The destinationParent index corresponds to the parent into which those columns are moved. The destinationChild is the column to which the columns will be moved. That is, the index at column sourceFirst in sourceParent will become column destinationChild in destinationParent, followed by all other columns up to sourceLast.

However, when moving columns down in the same parent (sourceParent and destinationParent are equal), the columns will be placed before the destinationChild index. That is, if you wish to move columns 0 and 1 so they will become columns 1 and 2, destinationChild should be 3. In this case, the new index for the source column i (which is between sourceFirst and sourceLast) is equal to (destinationChild-sourceLast-1+i).

Note that if sourceParent and destinationParent are the same, you must ensure that the destinationChild is not within the range of sourceFirst and sourceLast + 1. You must also ensure that you do not attempt to move a column to one of its own children or ancestors. This method returns false if either condition is true, in which case you should abort your move operation.

See also endMoveColumns().

[protected] bool QAbstractItemModel::beginMoveRows(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)

Begins a row move operation.

When reimplementing a subclass, this method simplifies moving entities in your model. This method is responsible for moving persistent indexes in the model, which you would otherwise be required to do yourself. Using beginMoveRows and endMoveRows is an alternative to emitting layoutAboutToBeChanged and layoutChanged directly along with changePersistentIndex.

The sourceParent index corresponds to the parent from which the rows are moved; sourceFirst and sourceLast are the first and last row numbers of the rows to be moved. The destinationParent index corresponds to the parent into which those rows are moved. The destinationChild is the row to which the rows will be moved. That is, the index at row sourceFirst in sourceParent will become row destinationChild in destinationParent, followed by all other rows up to sourceLast.

However, when moving rows down in the same parent (sourceParent and destinationParent are equal), the rows will be placed before the destinationChild index. That is, if you wish to move rows 0 and 1 so they will become rows 1 and 2, destinationChild should be 3. In this case, the new index for the source row i (which is between sourceFirst and sourceLast) is equal to (destinationChild-sourceLast-1+i).

Note that if sourceParent and destinationParent are the same, you must ensure that the destinationChild is not within the range of sourceFirst and sourceLast + 1. You must also ensure that you do not attempt to move a row to one of its own children or ancestors. This method returns false if either condition is true, in which case you should abort your move operation.

Moving rows to another parentSpecify the first and last row numbers for the span of rows in the source parent you want to move in the model. Also specify the row in the destination parent to move the span to.

For example, as shown in the diagram, we move three rows from row 2 to 4 in the source, so sourceFirst is 2 and sourceLast is 4. We move those items to above row 2 in the destination, so destinationChild is 2.

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

This moves the three rows rows 2, 3, and 4 in the source to become 2, 3 and 4 in the destination. Other affected siblings are displaced accordingly.

Moving rows to append to another parentTo append rows to another parent, move them to after the last row.

For example, as shown in the diagram, we move three rows to a collection of 6 existing rows (ending in row 5), so destinationChild is 6:

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

This moves the target rows to the end of the target parent as 6, 7 and 8.

Moving rows in the same parent upTo move rows within the same parent, specify the row to move them to.

For example, as shown in the diagram, we move one item from row 2 to row 0, so sourceFirst and sourceLast are 2 and destinationChild is 0.

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

Note that other rows may be displaced accordingly. Note also that when moving items within the same parent you should not attempt invalid or no-op moves. In the above example, item 2 is at row 2 before the move, so it cannot be moved to row 2 (where it is already) or row 3 (no-op as row 3 means above row 3, where it is already)

Moving rows in the same parent downTo move rows within the same parent, specify the row to move them to.

For example, as shown in the diagram, we move one item from row 2 to row 4, so sourceFirst and sourceLast are 2 and destinationChild is 4.

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

Note that other rows may be displaced accordingly.

See also endMoveRows().

[protected] void QAbstractItemModel::beginRemoveColumns(const QModelIndex &parent, int first, int last)

Begins a column removal operation.

When reimplementing removeColumns() in a subclass, you must call this function before removing data from the model's underlying data store.

The parent index corresponds to the parent from which the new columns are removed; first and last are the column numbers of the first and last columns to be removed.

Removing columnsSpecify the first and last column numbers for the span of columns you want to remove from an item in a model.

For example, as shown in the diagram, we remove the three columns from column 4 to column 6, so first is 4 and last is 6:

 beginRemoveColumns(parent, 4, 6);

Note: This function emits the columnsAboutToBeRemoved() signal which connected views (or proxies) must handle before the data is removed. Otherwise, the views may end up in an invalid state.

See also endRemoveColumns().

[protected] void QAbstractItemModel::beginRemoveRows(const QModelIndex &parent, int first, int last)

Begins a row removal operation.

When reimplementing removeRows() in a subclass, you must call this function before removing data from the model's underlying data store.

The parent index corresponds to the parent from which the new rows are removed; first and last are the row numbers of the rows to be removed.

Removing rowsSpecify the first and last row numbers for the span of rows you want to remove from an item in a model.

For example, as shown in the diagram, we remove the two rows from row 2 to row 3, so first is 2 and last is 3:

 beginRemoveRows(parent, 2, 3);

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

See also endRemoveRows().

[protected] void QAbstractItemModel::beginResetModel()

Begins a model reset operation.

A reset operation resets the model to its current state in any attached views.

Note: Any views attached to this model will be reset as well.

When a model is reset it means that any previous data reported from the model is now invalid and has to be queried for again. This also means that the current item and any selected items will become invalid.

When a model radically changes its data it can sometimes be easier to just call this function rather than emit dataChanged() to inform other components when the underlying data source, or its structure, has changed.

You must call this function before resetting any internal data structures in your model or proxy model.

This function emits the signal modelAboutToBeReset().

See also modelAboutToBeReset(), modelReset(), and endResetModel().

[virtual] QModelIndex QAbstractItemModel::buddy(const QModelIndex &index) const

Returns a model index for the buddy of the item represented by index. When the user wants to edit an item, the view will call this function to check whether another item in the model should be edited instead. Then, the view will construct a delegate using the model index returned by the buddy item.

The default implementation of this function has each item as its own buddy.

[virtual] bool QAbstractItemModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const

Returns true if a model can accept a drop of the data. This default implementation only checks if data has at least one format in the list of mimeTypes() and if action is among the model's supportedDropActions().

Reimplement this function in your custom model, if you want to test whether the data can be dropped at row, column, parent with action. If you don't need that test, it is not necessary to reimplement this function.

See also dropMimeData() and Using drag and drop with item views.

[virtual invokable] bool QAbstractItemModel::canFetchMore(const QModelIndex &parent) const

Returns true if there is more data available for parent; otherwise returns false.

The default implementation always returns false.

If canFetchMore() returns true, the fetchMore() function should be called. This is the behavior of QAbstractItemView, for example.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also fetchMore().

[protected] void QAbstractItemModel::changePersistentIndex(const QModelIndex &from, const QModelIndex &to)

Changes the QPersistentModelIndex that is equal to the given from model index to the given to model index.

If no persistent model index equal to the given from model index was found, nothing is changed.

See also persistentIndexList() and changePersistentIndexList().

[protected] void QAbstractItemModel::changePersistentIndexList(const QModelIndexList &from, const QModelIndexList &to)

Changes the {QPersistentModelIndex}es that are equal to the indexes in the given from model index list to the given to model index list.

If no persistent model indexes equal to the indexes in the given from model index list are found, nothing is changed.

See also persistentIndexList() and changePersistentIndex().

[since 5.11] bool QAbstractItemModel::checkIndex(const QModelIndex &index, QAbstractItemModel::CheckIndexOptions options = CheckIndexOption::NoOption) const

This function checks whether index is a legal model index for this model. A legal model index is either an invalid model index, or a valid model index for which all the following holds:

  • the index' model is this;
  • the index' row is greater or equal than zero;
  • the index' row is less than the row count for the index' parent;
  • the index' column is greater or equal than zero;
  • the index' column is less than the column count for the index' parent.

The options argument may change some of these checks. If options contains IndexIsValid, then index must be a valid index; this is useful when reimplementing functions such as data() or setData(), which expect valid indexes.

If options contains DoNotUseParent, then the checks that would call parent() are omitted; this allows calling this function from a parent() reimplementation (otherwise, this would result in endless recursion and a crash).

If options does not contain DoNotUseParent, and it contains ParentIsInvalid, then an additional check is performed: the parent index is checked for not being valid. This is useful when implementing flat models such as lists or tables, where no model index should have a valid parent index.

This function returns true if all the checks succeeded, and false otherwise. This allows to use the function in Q_ASSERT and similar other debugging mechanisms. If some check failed, a warning message will be printed in the qt.core.qabstractitemmodel.checkindex logging category, containing some information that may be useful for debugging the failure.

Note: This function is a debugging helper for implementing your own item models. When developing complex models, as well as when building complicated model hierarchies (e.g. using proxy models), it is useful to call this function in order to catch bugs relative to illegal model indices (as defined above) accidentally passed to some QAbstractItemModel API.

Warning: Note that it's undefined behavior to pass illegal indices to item models, so applications must refrain from doing so, and not rely on any "defensive" programming that item models could employ to handle illegal indexes gracefully.

This function was introduced in Qt 5.11.

See also QModelIndex.

[virtual, since 6.0] bool QAbstractItemModel::clearItemData(const QModelIndex &index)

Removes the data stored in all the roles for the given index. Returns true if successful; otherwise returns false. The dataChanged() signal should be emitted if the data was successfully removed. The base class implementation returns false

This function was introduced in Qt 6.0.

See also data(), itemData(), setData(), and setItemData().

[pure virtual invokable] int QAbstractItemModel::columnCount(const QModelIndex &parent = QModelIndex()) const

Returns the number of columns for the children of the given parent.

In most subclasses, the number of columns is independent of the parent.

For example:

 int DomModel::columnCount(const QModelIndex &parent) const
 {
     Q_UNUSED(parent);
     return 3;
 }

Note: When implementing a table based model, columnCount() should return 0 when the parent is valid.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also rowCount().

[protected] QModelIndex QAbstractItemModel::createIndex(int row, int column, const void *ptr = nullptr) const

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

When using a QSortFilterProxyModel, its indexes have their own internal pointer. It is not advisable 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.

[protected] QModelIndex QAbstractItemModel::createIndex(int row, int column, quintptr id) const

Creates a model index for the given row and column with the internal identifier, id.

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

See also QModelIndex::internalId().

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

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

Note: If you do not have a value to return, return an invalid QVariant instead of returning 0.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also Qt::ItemDataRole, setData(), and headerData().

[virtual] bool QAbstractItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)

Handles the data supplied by a drag and drop operation that ended with the given action.

Returns true if the data and action were handled by the model; otherwise returns false.

The specified row, column and parent indicate the location of an item in the model where the operation ended. It is the responsibility of the model to complete the action at the correct location.

For instance, a drop action on an item in a QTreeView can result in new items either being inserted as children of the item specified by row, column, and parent, or as siblings of the item.

When row and column are -1 it means that the dropped data should be considered as dropped directly on parent. Usually this will mean appending the data as child items of parent. If row and column are greater than or equal zero, it means that the drop occurred just before the specified row and column in the specified parent.

The mimeTypes() member is called to get the 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 your custom model to return multiple MIME types, you must reimplement this function to make use of them.

See also supportedDropActions(), canDropMimeData(), and Using drag and drop with item views.

[protected] void QAbstractItemModel::endInsertColumns()

Ends a column insertion operation.

When reimplementing insertColumns() in a subclass, you must call this function after inserting data into the model's underlying data store.

See also beginInsertColumns().

[protected] void QAbstractItemModel::endInsertRows()

Ends a row insertion operation.

When reimplementing insertRows() in a subclass, you must call this function after inserting data into the model's underlying data store.

See also beginInsertRows().

[protected] void QAbstractItemModel::endMoveColumns()

Ends a column move operation.

When implementing a subclass, you must call this function after moving data within the model's underlying data store.

See also beginMoveColumns().

[protected] void QAbstractItemModel::endMoveRows()

Ends a row move operation.

When implementing a subclass, you must call this function after moving data within the model's underlying data store.

See also beginMoveRows().

[protected] void QAbstractItemModel::endRemoveColumns()

Ends a column removal operation.

When reimplementing removeColumns() in a subclass, you must call this function after removing data from the model's underlying data store.

See also beginRemoveColumns().

[protected] void QAbstractItemModel::endRemoveRows()

Ends a row removal operation.

When reimplementing removeRows() in a subclass, you must call this function after removing data from the model's underlying data store.

See also beginRemoveRows().

[protected] void QAbstractItemModel::endResetModel()

Completes a model reset operation.

You must call this function after resetting any internal data structure in your model or proxy model.

This function emits the signal modelReset().

See also beginResetModel().

[virtual invokable] void QAbstractItemModel::fetchMore(const QModelIndex &parent)

Fetches any available data for the items with the parent specified by the parent index.

Reimplement this if you are populating your model incrementally.

The default implementation does nothing.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also canFetchMore().

[virtual invokable] Qt::ItemFlags QAbstractItemModel::flags(const QModelIndex &index) const

Returns the item flags for the given index.

The base class implementation returns a combination of flags that enables the item (ItemIsEnabled) and allows it to be selected (ItemIsSelectable).

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also Qt::ItemFlags.

[virtual invokable] bool QAbstractItemModel::hasChildren(const QModelIndex &parent = QModelIndex()) const

Returns true if parent has any children; otherwise returns false.

Use rowCount() on the parent to find out the number of children.

Note that it is undefined behavior to report that a particular index hasChildren with this method if the same index has the flag Qt::ItemNeverHasChildren set.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also parent() and index().

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

Returns true if the model returns a valid QModelIndex for row and column with parent, otherwise returns false.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

[virtual invokable] QVariant QAbstractItemModel::headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const

Returns the data for the given role and section in the header with the specified orientation.

For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also Qt::ItemDataRole, setHeaderData(), and QHeaderView.

[pure virtual invokable] QModelIndex QAbstractItemModel::index(int row, int column, const QModelIndex &parent = QModelIndex()) const

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

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

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also createIndex().

bool QAbstractItemModel::insertColumn(int column, const QModelIndex &parent = QModelIndex())

Inserts a single column before the given column in the child items of the parent specified.

Returns true if the column is inserted; otherwise returns false.

See also insertColumns(), insertRow(), and removeColumn().

[virtual] bool QAbstractItemModel::insertColumns(int column, int count, const QModelIndex &parent = QModelIndex())

On models that support this, inserts count new columns 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.

If column is 0, the columns are prepended to any existing columns.

If column is columnCount(), the columns are appended to any existing columns.

If parent has no children, a single row with count columns is inserted.

Returns true if the columns were successfully inserted; otherwise returns false.

The base class implementation does nothing and returns false.

If you implement your own model, you can reimplement this function if you want to support insertions. Alternatively, you can provide your own API for altering the data.

See also insertRows(), removeColumns(), beginInsertColumns(), and endInsertColumns().

bool QAbstractItemModel::insertRow(int row, const QModelIndex &parent = QModelIndex())

Inserts a single row before the given row in the child items of the parent specified.

Note: This function calls the virtual method insertRows.

Returns true if the row is inserted; otherwise returns false.

See also insertRows(), insertColumn(), and removeRow().

[virtual] bool QAbstractItemModel::insertRows(int row, int count, const QModelIndex &parent = QModelIndex())

Note: The base class implementation of this function does nothing and returns false.

On models that support this, inserts count rows into the model before the given row. Items in the new row will be children of the item represented by the parent model index.

If row is 0, the rows are prepended to any existing rows in the parent.

If row is rowCount(), the rows are appended to any existing rows in the parent.

If parent has no children, a single column with count rows is inserted.

Returns true if the rows were successfully inserted; otherwise returns false.

If you implement your own model, you can reimplement this function if you want to support insertions. Alternatively, you can provide your own API for altering the data. In either case, you will need to call beginInsertRows() and endInsertRows() to notify other components that the model has changed.

See also insertColumns(), removeRows(), beginInsertRows(), and endInsertRows().

[virtual] QMap<int, QVariant> QAbstractItemModel::itemData(const QModelIndex &index) const

Returns a map with values for all predefined roles in the model for the item at the given index.

Reimplement this function if you want to extend the default behavior of this function to include custom roles in the map.

See also setItemData(), Qt::ItemDataRole, and data().

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

Returns a list of indexes for the items in the column of the start index where data stored under the given role matches the specified value. The way the search is performed is defined by the flags given. The list that is returned may be empty. Note also that the order of results in the list may not correspond to the order in the model, if for example a proxy model is used. The order of the results cannot be relied upon.

The search begins from the start index, and continues until the number of matching data items equals hits, the search reaches the last row, or the search reaches start again - depending on whether MatchWrap is specified in flags. If you want to search for all matching items, use hits = -1.

By default, this function will perform a wrapping, string-based comparison on all items, searching for items that begin with the search term specified by value.

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

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

[virtual] QMimeData *QAbstractItemModel::mimeData(const QModelIndexList &indexes) const

Returns an object that contains serialized items of data corresponding to the list of indexes specified. The format used to describe the encoded data is obtained from the mimeTypes() function. This default implementation uses the default MIME type returned by the default implementation of mimeTypes(). If you reimplement mimeTypes() in your custom model to return more MIME types, reimplement this function to make use of them.

If the list of indexes is empty, or there are no supported MIME types, nullptr is returned rather than a serialized empty list.

See also mimeTypes() and dropMimeData().

[virtual] QStringList QAbstractItemModel::mimeTypes() const

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

When implementing drag and drop support in a custom model, if you will return data in formats other than the default internal MIME type, reimplement this function to return your list of MIME types.

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

See also mimeData() and dropMimeData().

bool QAbstractItemModel::moveColumn(const QModelIndex &sourceParent, int sourceColumn, const QModelIndex &destinationParent, int destinationChild)

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

Returns true if the columns were successfully moved; otherwise returns false.

See also moveColumns() and moveRow().

[virtual] bool QAbstractItemModel::moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destinationParent, int destinationChild)

On models that support this, moves count columns starting with the given sourceColumn under parent sourceParent to column destinationChild under parent destinationParent.

Returns true if the columns were successfully moved; otherwise returns false.

The base class implementation does nothing and returns false.

If you implement your own model, you can reimplement this function if you want to support moving. Alternatively, you can provide your own API for altering the data.

See also beginMoveColumns() and endMoveColumns().

bool QAbstractItemModel::moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild)

On models that support this, moves sourceRow from sourceParent to destinationChild under destinationParent.

Returns true if the rows were successfully moved; otherwise returns false.

See also moveRows() and moveColumn().

[virtual] bool QAbstractItemModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild)

On models that support this, moves count rows starting with the given sourceRow under parent sourceParent to row destinationChild under parent destinationParent.

Returns true if the rows were successfully moved; otherwise returns false.

The base class implementation does nothing and returns false.

If you implement your own model, you can reimplement this function if you want to support moving. Alternatively, you can provide your own API for altering the data.

See also beginMoveRows() and endMoveRows().

[virtual, since 6.0] void QAbstractItemModel::multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const

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

The default implementation will call simply data() for each role in the span. A subclass can reimplement this function to provide data to views more efficiently:

 void MyModel::multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const
 {
     for (QModelRoleData &roleData : roleDataSpan) {
         int role = roleData.role();

         // ... obtain the data for index and role ...

         roleData.setData(result);
     }
 }

In the snippet above, index is the same for the entire call. This means that accessing to the necessary data structures in order to retrieve the information for index can be done only once (hoisting the relevant code out of the loop).

The usage of QModelRoleData::setData(), or similarly QVariant::setValue(), is encouraged over constructing a QVariant separately and using a plain assignment operator; this is because the former allow to re-use the memory already allocated for the QVariant object stored inside a QModelRoleData, while the latter always allocates the new variant and then destroys the old one.

Note that views may call multiData() with spans that have been used in previous calls, and therefore may already contain some data. Therefore, it is imperative that if the model cannot return the data for a given role, then it must clear the data in the corresponding QModelRoleData object. This can be done by calling QModelRoleData::clearData(), or similarly by setting a default constructed QVariant, and so on. Failure to clear the data will result in the view believing that the "old" data is meant to be used for the corresponding role.

Finally, in order to avoid code duplication, a subclass may also decide to reimplement data() in terms of multiData(), by supplying a span of just one element:

 QVariant MyModel::data(const QModelIndex &index, int role) const
 {
     QModelRoleData roleData(role);
     multiData(index, roleData);
     return roleData.data();
 }

Note: Models are not allowed to modify the roles in the span, or to rearrange the span elements. Doing so results in undefined behavior.

Note: It is illegal to pass an invalid model index to this function.

This function was introduced in Qt 6.0.

See also QModelRoleDataSpan and data().

[pure virtual invokable] QModelIndex QAbstractItemModel::parent(const QModelIndex &index) const

Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned.

A common convention used in models that expose tree data structures is that only items in the first column have children. For that case, when reimplementing this function in a subclass the column of the returned QModelIndex would be 0.

When reimplementing this function in a subclass, be careful to avoid calling QModelIndex member functions, such as QModelIndex::parent(), since indexes belonging to your model will simply call your implementation, leading to infinite recursion.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also createIndex().

[protected] QModelIndexList QAbstractItemModel::persistentIndexList() const

Returns the list of indexes stored as persistent indexes in the model.

bool QAbstractItemModel::removeColumn(int column, const QModelIndex &parent = QModelIndex())

Removes the given column from the child items of the parent specified.

Returns true if the column is removed; otherwise returns false.

See also removeColumns(), removeRow(), and insertColumn().

[virtual] bool QAbstractItemModel::removeColumns(int column, int count, const QModelIndex &parent = QModelIndex())

On models that support this, removes count columns starting with the given column under parent parent from the model.

Returns true if the columns were successfully removed; otherwise returns false.

The base class implementation does nothing and returns false.

If you implement your own model, you can reimplement this function if you want to support removing. Alternatively, you can provide your own API for altering the data.

See also removeColumn(), removeRows(), insertColumns(), beginRemoveColumns(), and endRemoveColumns().

bool QAbstractItemModel::removeRow(int row, const QModelIndex &parent = QModelIndex())

Removes the given row from the child items of the parent specified.

Returns true if the row is removed; otherwise returns false.

This is a convenience function that calls removeRows(). The QAbstractItemModel implementation of removeRows() does nothing.

See also removeRows(), removeColumn(), and insertRow().

[virtual] bool QAbstractItemModel::removeRows(int row, int count, const QModelIndex &parent = QModelIndex())

On models that support this, removes count rows starting with the given row under parent parent from the model.

Returns true if the rows were successfully removed; otherwise returns false.

The base class implementation does nothing and returns false.

If you implement your own model, you can reimplement this function if you want to support removing. Alternatively, you can provide your own API for altering the data.

See also removeRow(), removeColumns(), insertColumns(), beginRemoveRows(), and endRemoveRows().

[virtual] QHash<int, QByteArray> QAbstractItemModel::roleNames() const

Returns the model's role names.

The default role names set by Qt are:

Qt RoleQML Role Name
Qt::DisplayRoledisplay
Qt::DecorationRoledecoration
Qt::EditRoleedit
Qt::ToolTipRoletoolTip
Qt::StatusTipRolestatusTip
Qt::WhatsThisRolewhatsThis

[pure virtual invokable] int QAbstractItemModel::rowCount(const QModelIndex &parent = QModelIndex()) const

Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent.

Note: When implementing a table based model, rowCount() should return 0 when the parent is valid.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also columnCount().

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

Sets the role data for the item at index to value.

Returns true if successful; otherwise returns false.

The dataChanged() signal should be emitted if the data was successfully set.

The base class implementation returns false. This function and data() must be reimplemented for editable models.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also Qt::ItemDataRole, data(), and itemData().

[virtual] bool QAbstractItemModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole)

Sets the data for the given role and section in the header with the specified orientation to the value supplied.

Returns true if the header's data was updated; otherwise returns false.

When reimplementing this function, the headerDataChanged() signal must be emitted explicitly.

See also Qt::ItemDataRole and headerData().

[virtual] bool QAbstractItemModel::setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles)

Sets the role data for the item at index to the associated value in roles, for every Qt::ItemDataRole.

Returns true if successful; otherwise returns false.

Roles that are not in roles will not be modified.

See also setData(), data(), and itemData().

[virtual invokable] QModelIndex QAbstractItemModel::sibling(int row, int column, const QModelIndex &index) const

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

sibling() is just a convenience function that finds the item's parent, and uses it to retrieve the index of the child item in the specified row and column.

This method can optionally be overridden for implementation-specific optimization.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also index(), QModelIndex::row(), and QModelIndex::column().

[virtual] void QAbstractItemModel::sort(int column, Qt::SortOrder order = Qt::AscendingOrder)

Sorts the model by column in the given order.

The base class implementation does nothing.

[virtual] QSize QAbstractItemModel::span(const QModelIndex &index) const

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

Note: Currently, span is not used.

[virtual] Qt::DropActions QAbstractItemModel::supportedDragActions() const

Returns the actions supported by the data in this model.

The default implementation returns supportedDropActions(). Reimplement this function if you wish to support additional actions.

supportedDragActions() is used by QAbstractItemView::startDrag() as the default values when a drag occurs.

See also Qt::DropActions and Using drag and drop with item views.

[virtual] Qt::DropActions QAbstractItemModel::supportedDropActions() const

Returns the drop actions supported by this model.

The default implementation returns Qt::CopyAction. Reimplement this function if you wish to support additional actions. You must also reimplement the dropMimeData() function to handle the additional operations.

See also dropMimeData(), Qt::DropActions, and Using drag and drop with item views.