我有以下简单的模型示例:
#include <QtGui/QApplication>
#include <QtGui/QTreeView>
#include <QAbstractItemModel>
class TestModel : public QAbstractItemModel
{
public:
TestModel()
{
SetUpData();
}
virtual QModelIndex index(int row, int column, const QModelIndex& parent) const
{
if ( parent.isValid())
{
// child
return createIndex( row, column, (void*)&mData[row].mChildren[column]);
}
// root
return createIndex( row, column, (void*)&mData[row]);
}
virtual QModelIndex parent(const QModelIndex& child) const
{
ModelData* data = (ModelData*)child.internalPointer();
// find out where "data" is in the mData vector structure
for ( size_t i=0; i<mData.size(); ++i )
{
for ( size_t j=0; j<mData[i].mChildren.size(); ++j )
{
if ( &mData[i].mChildren[j] == data )
{
// I think this is correct, return the parent row at col 0?
return createIndex( i, 0, (void*)&mData[i].mChildren[j]);
}
}
}
return QModelIndex();
}
virtual int rowCount(const QModelIndex& parent) const
{
if ( parent.isValid() )
{
// Per root node size
return mData[parent.row()].mChildren.size();
}
// Root size
return mData.size();
}
virtual int columnCount(const QModelIndex& parent) const
{
// The "parent" nodes should have two columns, the children should have 1
if ( parent.isValid() )
{
// Root
return 1;
}
// Children
return 2;
}
virtual QVariant data(const QModelIndex& index, int role) const
{
if ( role == Qt::DisplayRole && index.isValid() )
{
if ( index.isValid() )
{
// I think col and row are the wrong way around, but will crash if swapped
return mData[index.column()].mChildren[index.row()].mName;
}
else
{
// this never happens because "RootN" is never displayed
return mData[index.column()].mName;
}
}
return QVariant();
}
private:
// The "real" data that this Qt model is providing an interface to
struct ModelData
{
QString mName;
std::vector< ModelData > mChildren;
};
std::vector< ModelData > mData;
void SetUpData()
{
for ( int i=0; i<3; ++i )
{
ModelData root;
root.mName = "Root" + QString::number( i+1 );
for ( int j=0; j<10; ++j )
{
ModelData node;
node.mName = "Node" + QString::number( j+1 );
root.mChildren.push_back( node );
}
mData.push_back( root );
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TestModel* model = new TestModel();
QTreeView* tv = new QTreeView();
tv->setModel( model );
tv->show();
int ret = a.exec();
delete tv;
delete model;
return ret;
}
我在这里要做的是创建一个具有以下结构的模型:
Root1
|-Node1-10
|
Root2
|-Node1-10
|
Root3
|-Node1-10
但是我最终得到了这个:
我真的很困惑索引/父级和数据应该如何工作。显然我不明白,因为我的输出不正确。
我认为,例如,Root1、Node3 会导致使用 row = 0、col=2 调用索引,此时我使用 0,2 和指向该元素的指针调用 createIndex?
对于 parent(),如果 parent 有效,则返回 QModelIndex,因为这意味着它是一个 RootN 元素,如果它不是根元素,则返回 createIndex 以创建到 parent 的索引。
最后对于数据,我认为这只是返回给定行/列的 UI 的显示字符串?