gpt4 book ai didi

c++ - modeltest + 简单表模式 = 父测试失败

转载 作者:太空狗 更新时间:2023-10-29 20:51:16 24 4
gpt4 key购买 nike

这里是我的模型的简化版本:

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 是私有(private)的。QAbstractTableModel 是否为 QTableView 的数据建模提供了错误的基础?

最佳答案

QAbstractItemModel::rowCountQAbstractItemModel::columnCount 的接口(interface)允许 View 向模型询问顶级行/列的数量以及询问对于特定节点的子节点数。前者通过传入一个 invalid 来完成。 parent,而后者是通过将特定节点的QModelIndex作为parent参数传递来完成的。

您的 TableModel::rowCount 的实现始终返回 1,即使 View 传递了一个有效的 parent(即它要求另一个节点的子节点数)。由于这应该是一个“表”模型(而不是树模型),您应该按如下方式更改您的 rowCountcolumnCount:

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 通过获取第一个 child 来检测此类错误QModelIndex 从您的模型中获取根索引 (0,0),然后询问这个 child 关于它的 parent .报告的父级应该等于根索引(显然,这在您的代码中失败,因为您没有维护任何这些关系)...

关于c++ - modeltest + 简单表模式 = 父测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50987823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com