Qt QAbstractItemModel类详解

一.概述

QAbstractItemModel 类定义了项目模型必须使用的标准接口,以便能够与模型/视图Model/View框架中的其他组件进行互操作。 正确用法是将其子类化以创建新模型。此类用作 QML 中的项目视图元素或 Qt Widgets 模块中的项目视图类的底层数据模型。如果需要一个模型与项目视图一起使用,例如 QML 的列表视图元素或 C++控件QListViewQTableView,则应该考虑子类化QAbstractListModelQAbstractTableModel 而不是此类。底层数据模型作为表的层次结构向视图和委托公开。 如果不使用层次结构,那么模型就是一个简单的行和列表。每个项目都有一个由 QModelIndex 指定的唯一索引。
在这里插入图片描述
可以通过模型访问的每个数据项都有一个关联的模型索引。可以使用index()函数获取此模型索引。每个索引可以有一个sibling()索引;子项具有parent()索引。

二.QAbstractItemModel类

1.类型

类型原型说明
enum classCheckIndexOption { NoOption, IndexIsValid, DoNotUseParent, ParentIsInvalid }此枚举可用于控制由 checkIndex() (此函数检查 index 是否是该模型的合法模型索引)执行的检查。
flagsCheckIndexOptions
enumLayoutChangeHint { NoLayoutChangeHint, VerticalSortHint, HorizontalSortHint }此枚举描述模型更改布局的方式

2.信号

返回值信号说明
voidcolumnsAboutToBeInserted(const QModelIndex &parent, int first, int last)该信号在列插入模型之前发出。新项目将位于给定parent下的first和last之间。
voidcolumnsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationColumn)该信号在列在模型内移动之前发出。将被移动的项目是在给定的 sourceParent 项目下的 sourceStart 和 sourceEnd 之间的项目。 它们将被移动到destinationParent,从destinationColumn 列开始。
voidcolumnsAboutToBeRemoved(const QModelIndex &parent, int first, int last)该信号在列从模型中移除之前发出。要删除的项目是在给定 parent 下的 first 和 last 之间的项目。
voidcolumnsInserted(const QModelIndex &parent, int first, int last)在将列插入模型之后发出此信号。新项目是在给定parent下的first和last之间的项目。
voidcolumnsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int column)在模型内移动列之后发出此信号。给parent下的 start 和 end 之间的项目已移至 column 列开始的destination。
voidcolumnsRemoved(const QModelIndex &parent, int first, int last)从模型中删除列后会发出此信号。 删除的项目是在给parent下的first和last之间的项目。
voiddataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList &roles = QList())只要现有项目中的数据发生变化,就会发出此信号。
voidheaderDataChanged(Qt::Orientation orientation, int first, int last)每当更改标题时都会发出此信号。
voidlayoutAboutToBeChanged(const QList &parents = QList(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)该信号在模型布局更改之前发出。
voidlayoutChanged(const QList &parents = QList(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)每当模型公开的项目布局发生变化时,就会发出此信号(例如,当模型已经排序)。
voidmodelAboutToBeReset()在调用 beginResetModel() 时,在模型的内部状态(例如,持久模型索引)失效之前,会发出此信号。
voidmodelReset()在模型的内部状态(例如,持久模型索引)失效后,调用 endResetModel() 时会发出此信号。
voidrowsAboutToBeInserted(const QModelIndex &parent, int start, int end)该信号在行插入模型之前发出。新项目在给定的parent下将被定位在start和end之间。
voidrowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)该信号在行在模型内移动之前发出。将被移动的项目是在给定的 sourceParent 项目下的 sourceStart 和 sourceEnd 之间的项目。 它们将被移动到destinationParent 行,从destinationRow 开始。
voidrowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)该信号在行从模型中移除之前发出。 将被删除的项目是在给定parent下的first和last之间的项目。
voidrowsInserted(const QModelIndex &parent, int first, int last)在将行插入模型后发出此信号。新项目是在给定parent下的first和last之间的项目。
voidrowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row)在模型内移动行后发出此信号。 给定parent下的 start 和 end 之间的项已移动到从row行开始的destination。
voidrowsRemoved(const QModelIndex &parent, int first, int last)从模型中删除行后会发出此信号。删除的项目是在给定parent下的first和last之间的项目。

3.函数

返回值函数说明
QAbstractItemModel(QObject *parent = nullptr)
virtual~QAbstractItemModel()
virtual QModelIndexbuddy(const QModelIndex &index) const返回由index表示的项目的好友模型索引。
virtual boolcanDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const如果模型可以接受拖拽数据,则返回 true。
virtual boolcanFetchMore(const QModelIndex &parent) const如果父级有更多可用数据,则返回 true。默认实现始终返回 false。
boolcheckIndex(const QModelIndex &index, QAbstractItemModel::CheckIndexOptions options = CheckIndexOption::NoOption) const此函数检查 index 是否是该模型的合法模型索引。
virtual boolclearItemData(const QModelIndex &index)删除存储在给定索引的所有角色中的数据。成功则返回true。如果成功删除数据,则应发出 dataChanged() 信号。
virtual intcolumnCount(const QModelIndex &parent = QModelIndex()) const = 0返回给定父级的子级的列数。
virtual QVariantdata(const QModelIndex &index, int role = Qt::DisplayRole) const = 0返回存储在给定角色下的数据,用于索引引用的项目。
virtual booldropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)处理拖放拖入的数据。
virtual voidfetchMore(const QModelIndex &parent)获取具有由父索引指定的父项的项的任何可用数据。如果以增量方式填充模型,需要重新实现它。
virtual Qt::ItemFlagsflags(const QModelIndex &index) const返回给定索引的项目标志。
virtual boolhasChildren(const QModelIndex &parent = QModelIndex()) constparent 是否有子项。
boolhasIndex(int row, int column, const QModelIndex &parent = QModelIndex()) const如果模型为具有父级的行和列返回有效的 QModelIndex,则返回 true。
virtual QVariantheaderData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const返回具有指定方向的标题中给定角色和部分的数据。对于水平标题,节号对应于列号。 同样,对于垂直标题,节号对应于行号。
virtual QModelIndexindex(int row, int column, const QModelIndex &parent = QModelIndex()) const = 0返回由给定的行、列和父索引指定的模型中项目的索引。
boolinsertColumn(int column, const QModelIndex &parent = QModelIndex())在指定的父项的子项中的给定列之前插入单列。如果成功插入了列则返回 true。
virtual boolinsertColumns(int column, int count, const QModelIndex &parent = QModelIndex())上面函数的重载函数
boolinsertRow(int row, const QModelIndex &parent = QModelIndex())在指定的父项的子项中的给定行之前插入单行。如果成功插入了列则返回 true。
virtual boolinsertRows(int row, int count, const QModelIndex &parent = QModelIndex())上面函数的重载函数
virtual QMap<int, QVariant>itemData(const QModelIndex &index) const返回一个map,其中包含index处的项目的模型中所有预定义角色的值。
virtual QModelIndexListmatch(const QModelIndex &start, int role, const QVariant &value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWithQt::MatchWrap)) const
virtual QMimeData *mimeData(const QModelIndexList &indexes) const返回一个对象,其中包含与指定索引列表相对应的序列化数据项。用于描述编码数据的格式是从 mimeTypes() 函数获得的。
virtual QStringListmimeTypes() const返回允许的 MIME 类型列表。
boolmoveColumn(const QModelIndex &sourceParent, int sourceColumn, const QModelIndex &destinationParent, int destinationChild)在支持此功能的模型上,将 sourceColumn 从 sourceParent 移动到 destinationParent 下的 destinationChild。
virtual boolmoveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destinationParent, int destinationChild)在支持此功能的模型上,将从父 sourceParent 下的给定 sourceColumn 开始的列移动到父 destinationParent 下的列 destinationChild。
boolmoveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild)在支持此功能的模型上,将从父 sourceParent 下的给定 sourceColumn 开始的行移动到父 destinationParent 下的行 destinationChild。
virtual boolmoveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild)在支持此功能的模型上,将从父 sourceParent 下的给定 sourceColumn 开始的行移动到父 destinationParent 下的行 destinationChild。
virtual voidmultiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const使用给定索引的请求数据填充 roleDataSpan。
virtual QModelIndexparent(const QModelIndex &index) const = 0返回具有给定索引的模型项的父项。
boolremoveColumn(int column, const QModelIndex &parent = QModelIndex())从指定的父项的子项中删除给定列。如果列被删除返回 true。
virtual boolremoveColumns(int column, int count, const QModelIndex &parent = QModelIndex())在支持此功能的模型上,从模型中删除 parent 下的给定 column 开头的 count列。如果列被成功删除则返回 true。
boolremoveRow(int row, const QModelIndex &parent = QModelIndex())从指定的父项的子项中删除给定行。如果行被删除返回 true。
virtual boolremoveRows(int row, int count, const QModelIndex &parent = QModelIndex())在支持此功能的模型上,从模型中删除 parent 下的给定 row 开头的 count列。如果行被成功删除则返回 true。
virtual QHash<int, QByteArray>roleNames() const返回模型的角色名称。
virtual introwCount(const QModelIndex &parent = QModelIndex()) const = 0返回给定父项下的行数。
virtual boolsetData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole)设置索引处项目的角色数据。成功则返回true。如果成功设置了数据,则应发出 dataChanged() 信号。
virtual boolsetHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole)设置标题的值。如果标题的数据已更新则返回 true。
virtual boolsetItemData(const QModelIndex &index, const QMap<int, QVariant> &roles)对于每个 Qt::ItemDataRole,将 index 处项目的角色数据设置为角色中的关联值。不在角色中的角色将不会被修改。
virtual QModelIndexsibling(int row, int column, const QModelIndex &index) const返回索引处项目的行和列的兄弟,如果该位置没有兄弟,则返回无效的 QModelIndex。
virtual voidsort(int column, Qt::SortOrder order = Qt::AscendingOrder)按给定顺序按列对模型进行排序。
virtual QSizespan(const QModelIndex &index) const返回由索引表示的项目的行和列跨度。
virtual Qt::DropActionssupportedDragActions() const返回此模型中数据支持的操作。
virtual Qt::DropActionssupportedDropActions() const返回此模型支持的放置操作。
返回值函数说明
voidbeginInsertColumns(const QModelIndex &parent, int first, int last)开始列插入操作。
voidbeginInsertRows(const QModelIndex &parent, int first, int last)开始行插入操作。
boolbeginMoveColumns(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)开始列移动操作。
boolbeginMoveRows(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)开始行移动操作。
voidbeginRemoveColumns(const QModelIndex &parent, int first, int last)开始列移除操作。
voidbeginRemoveRows(const QModelIndex &parent, int first, int last)开始行移除操作。
voidbeginResetModel()开始模型重置操作。
voidchangePersistentIndex(const QModelIndex &from, const QModelIndex &to)
voidchangePersistentIndexList(const QModelIndexList &from, const QModelIndexList &to)
QModelIndexcreateIndex(int row, int column, const void *ptr = nullptr) const使用内部指针 ptr 为给定的行和列创建模型索引。
QModelIndexcreateIndex(int row, int column, quintptr id) const上面函数的重载函数
voidendInsertColumns()结束列插入操作。
voidendInsertRows()结束行插入操作。
voidendMoveColumns()结束列移动操作。
voidendMoveRows()结束行移动操作。
voidendRemoveColumns()结束列移除操作。
voidendRemoveRows()结束行删除操作。
voidendResetModel()完成模型重置操作。
QModelIndexListpersistentIndexList() const返回在模型中存储为持久索引的索引列表。
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现自定义的QAbstractItemModel,需要继承QAbstractItemModel并实现其虚函数。下面是一个示例: ```python from PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt class MyModel(QAbstractItemModel): def __init__(self, data, parent=None): super().__init__(parent) self.rootNode = Node(None, "Root") self.setupModel(data.split('\n'), self.rootNode) def setupModel(self, lines, parentNode): parents = [parentNode] indentations = [0] for line in lines: strippedLine = line.strip() indentation = line.count('\t') strippedLine = strippedLine.replace('\t', '') if not strippedLine: continue node = Node(parents[-1], strippedLine) if indentation > indentations[-1]: parents.append(parents[-1].child(parents[-1].childCount() - 1)) indentations.append(indentation) elif indentation < indentations[-1]: while indentation < indentations[-1] and len(parents) > 0: parents.pop() indentations.pop() parents[-1].appendChild(node) def index(self, row, column, parent=QModelIndex()): if not self.hasIndex(row, column, parent): return QModelIndex() if not parent.isValid(): parentNode = self.rootNode else: parentNode = parent.internalPointer() childNode = parentNode.child(row) if childNode: return self.createIndex(row, column, childNode) else: return QModelIndex() def parent(self, index): if not index.isValid(): return QModelIndex() childNode = index.internalPointer() parentNode = childNode.parent() if parentNode == self.rootNode: return QModelIndex() return self.createIndex(parentNode.row(), 0, parentNode) def rowCount(self, parent=QModelIndex()): if parent.column() > 0: return 0 if not parent.isValid(): parentNode = self.rootNode else: parentNode = parent.internalPointer() return parentNode.childCount() def columnCount(self, parent=QModelIndex()): return 1 def data(self, index, role): if not index.isValid(): return None node = index.internalPointer() if role == Qt.DisplayRole or role == Qt.EditRole: return node.name() return None class Node(object): def __init__(self, parent, name): self._name = name self._parent = parent self._children = [] if parent is not None: parent.appendChild(self) def appendChild(self, child): self._children.append(child) def child(self, row): return self._children[row] def childCount(self): return len(self._children) def parent(self): return self._parent def row(self): if self._parent is not None: return self._parent._children.index(self) return 0 def name(self): return self._name ``` 在这个示例中,我们实现了一个树形模型,用于显示一个包含缩进的文本文件。在构造函数中,我们调用了`setupModel`方法来设置节点和它们的父子关系。`index`、`parent`、`rowCount`、`columnCount`和`data`是QAbstractItemModel中的虚函数,我们在自定义的MyModel中实现这些函数。我们还实现了一个Node来表示节点,它包含节点的名称、父节点和子节点。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值