代码之家  ›  专栏  ›  技术社区  ›  user1244932

modeltest+simple table mode=父测试失败

  •  3
  • user1244932  · 技术社区  · 6 年前

    以下是我的模型的简化版本:

    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 ?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Mike    6 年前

    QAbstractItemModel::rowCount QAbstractItemModel::columnCount 的接口允许视图向模型询问顶级行/列的数量,并询问特定节点拥有的子节点的数量。前者是通过传入 invalid parent ,而后者是通过传递特定节点的 QModelIndex 作为 起源 参数。

    你的 TableModel::rowCount 的实现总是返回 1 即使视图通过有效的 起源 (即它要求另一个节点的子节点的数目)。因为这应该是一个“表”模型(不是一个树模型),所以你应该改变你的模型。 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 通过获取第一个 child QMODEL索引 对于模型的根索引(0,0),然后询问此子项 parent 。报告的父级应该等于根索引(很明显,这在代码中失败,因为您不维护这些关系中的任何一个)…