我试图实现一个模型,其中不同的第一级父母拥有不同大小的子表。在这段代码中,只有一个第一级父索引和子表8到8,并且应用程序在显示明显错误和缓慢时,尽管数据是正确的。我做错了什么?
testqtmodel.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = testqtmodel
TEMPLATE = app
SOURCES += main.cpp
的main.cpp
#include <QApplication>
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
#include <QTableView>
class TreeModel : public QAbstractItemModel
{
public:
explicit TreeModel(QObject *parent = 0)
: QAbstractItemModel(parent)
{
for (int i = 0; i < 8; ++i)
for (int j = 0; j < 8; ++j)
foo[i][j] = i + j;
}
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE
{
if (!index.isValid())
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
if (index.internalId() == 0)
return QVariant();
if (index.internalId() == 1)
return foo[index.row()][index.column()];
}
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE
{
if (!parent.isValid())
return createIndex(row, column, (quint64)0);
else
return createIndex(row, column, (quint64)1);
}
QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE
{
if (index.internalId() == 0)
return QModelIndex();
if (index.internalId() == 1)
return createIndex(0, 0, (quint64)0);
}
int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE
{
if (!parent.isValid())
return 1;
if (parent.internalId() == 0)
return 8;
}
int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE
{
if (!parent.isValid())
return 1;
if (parent.internalId() == 0)
return 8;
}
private:
int foo[8][8];
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView *v = new QTableView();
TreeModel *m = new TreeModel();
v->setModel(m);
v->setRootIndex(m->index(1, 1));
v->show();
return a.exec();
}
答案 0 :(得分:0)
我绝对是个傻瓜
v->setRootIndex(m->index(1, 1));
应该是
v->setRootIndex(m->index(0, 0));