我正在使用 Qt5 编写一个程序,该程序在 Linux 上运行良好,但在 Windows 上我观察到奇怪的行为:
当QTreeView::setModel
被调用时,它向模型询问索引( QAbstractItemModel::index
),其中包含一些行和列以及无效的父级。
它从未在 Linux 上发生过, View 总是要求 hasChildren
, rowCount
等在调用 index
之前.
我已经下载了 Qt5 的源代码来查看发生了什么,我可以看到:
// These asserts do basic sanity checking of the model
Q_ASSERT_X(d->model->index(0,0) == d->model->index(0,0),
"QAbstractItemView::setModel",
"A model should return the exact same index "
"(including its internal id/pointer) when asked for it twice in a row.");
Q_ASSERT_X(!d->model->index(0,0).parent().isValid(),
"QAbstractItemView::setModel",
"The parent of a top level index should be invalid");
我在 View 类或模型类的文档中找不到关于这些健全性检查的一个词。
它们在哪里定义?
这里的另一个有趣的事情是,我可以通过观察我编写的模型/ View 类来推断顶部索引应该是无效的,但我无法直接在文档中找到这些信息。
最佳答案
来自 QAbstractItemModel::parent()
的文档:
If the item has no parent, an invalid QModelIndex is returned.
这意味着调用
index()
具有无效 QModelIndex 的请求顶级项目。您遇到的健全性检查可能已在 Linux 中禁用(可能是发布版本?) - 但您的模型的功能绝不应该取决于函数调用的顺序。
如果
index()
使用无效的行/列参数调用(如果您的模型尚未填充),返回 QModelIndex()
.
关于qt - QAbstractItemView 向模型询问无效索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25326875/