以下是我的模型的简化版本:
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::父级
是私人的。
是
QAbstractTableModel
错误的数据建模基础
QTableView
?