这是我模型的简化版:
class TableModel : public QAbstractTableModel {
public:
TableModel(QObject *parent = nullptr) : QAbstractTableModel(parent) {
}
int rowCount(const QModelIndex &parent) const override { return 1; }
int columnCount(const QModelIndex &parent) const override { return 2; }
QVariant data(const QModelIndex &idx, int role) const override { return {}; }
};
如果我以这种方式(使用Qt model test)运行它:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
TableModel tbl_model;
ModelTest mtest{&tbl_model, nullptr};
}
它在以下位置失败:
// Common error test #1, make sure that a top level index has a parent
// that is a invalid QModelIndex.
QModelIndex topIndex = model->index(0, 0, QModelIndex());
tmp = model->parent(topIndex);
Q_ASSERT(tmp == QModelIndex());
// Common error test #2, make sure that a second level index has a parent
// that is the first level index.
if (model->rowCount(topIndex) > 0) {
QModelIndex childIndex = model->index(0, 0, topIndex);
qDebug() << "childIndex: " << childIndex;
tmp = model->parent(childIndex);
qDebug() << "tmp: " << tmp;
qDebug() << "topIndex: " << topIndex;
Q_ASSERT(tmp == topIndex);//assert failed
}
并打印:
childIndex: QModelIndex(0,0,0x0,QAbstractTableModel(0x7ffd7e2c05a0))
tmp: QModelIndex(-1,-1,0x0,QObject(0x0))
topIndex: QModelIndex(0,0,0x0,QAbstractTableModel(0x7ffd7e2c05a0))
我不明白如何修改我的模型以解决此问题?
看起来像是QAbstractTableModel::parent
中的问题,
换句话说,在Qt代码中,QAbstractTableModel::parent
是私有的。
QAbstractTableModel
是QTableView
数据建模的错误基础吗?
答案 0 :(得分:4)
QAbstractItemModel::rowCount
和QAbstractItemModel::columnCount
的界面允许视图向模型询问顶层行/列的数目,以及询问特定节点具有的子级数目。前者通过传递invalid parent
来完成,而后者通过传递特定节点的QModelIndex
作为parent
参数来完成。
即使视图通过有效的TableModel::rowCount
(即,它要求另一个节点的子代数),您的1
的实现也始终返回parent
。由于这应该是“表格”模型(而不是树模型),因此您应按以下方式更改rowCount
和columnCount
:
class TableModel : public QAbstractTableModel {
// .....
int rowCount(const QModelIndex &parent) const override {
if(parent.isValid()) return 0; //no children
return 1;
}
int columnCount(const QModelIndex &parent) const override {
if(parent.isValid()) return 0; //no children
return 2;
}
//....
}
ModelTest
通过从模型中获取根索引(0,0)的第一个child QModelIndex
,然后向该子节点询问其parent来检测此类错误。报告的父级应该等于根索引(显然,由于您未维护任何这些关系,因此这在您的代码中将失败)...