我正在使用Qt5编写程序,这在Linux上工作正常但在Windows上我观察到了奇怪的行为:
当调用QTreeView::setModel
时,它向模型询问索引(QAbstractItemModel::index
),其中包含一些行和列以及无效的父级。
它永远不会发生在Linux上,在调用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");
我无法在视图类和模型类的文档中找到关于那些健全性检查的单词。
他们在哪里定义?
另一个有趣的事情是,我可以通过观察模型/视图类来推断我已经写过顶级索引应该是无效的但我无法直接在文档中找到这些信息。
答案 0 :(得分:1)
摘自QAbstractItemModel::parent()
的文档:
如果该项没有父项,则返回无效的QModelIndex。
这意味着使用无效的QModelIndex调用index()
会要求提供顶级商品。
您遇到的健全性检查可能已在Linux中禁用(也许是发布版本?)-但是模型的功能绝不取决于函数调用的顺序。
如果使用无效的行/列参数调用了index()
(同样还没有填充您的模型),请返回QModelIndex()
。