2012-03-24 46 views
0

我在我的TableModel类中添加了addFile函数,它在最后插入一条新记录。QAbstactTableModel顶部插入

void TableModel::addFile(const QString &path) 
{ 
    beginInsertRows(QModelIndex(), list.size(),list.size()); 
    TableItem item; 
    item.filename = path; 
    QFile file(path); 
    item.size = file.size(); 
    item.status = StatusNew; 
    list << item; 
    endInsertRows(); 
} 

该函数可以正常工作,但不是在最后追加记录,而是想将其插入顶部。任何指针如何更新我现有的功能?

我已经尝试了一些组合,但没有运气。

+0

你想只显示开头插入的内容或你想要列表进行排序这种方式呢? – Gangadhar 2012-03-24 07:41:18

+0

两者 - 既然现有的代码处理两者 – Hiren 2012-03-24 07:52:00

回答

0

感谢大家的回复。我发现我自己的解决方案:

在情况下,如果有人有兴趣

void TableModel::addFile(const QString &path) 
{ 
    beginInsertRows(QModelIndex(), list.size(), list.size()); 
    TableItem item; 
    item.filename = path; 
    QFile file(path); 
    item.size = file.size(); 
    item.status = StatusNew; 
    list << item; // Why Assign first? Maybe not required 
    for (int i = list.size() - 1; i > 0; i--) 
    { 
     list[i] = list[i-1]; 
    } 
    list[0] = item; // set newly added item at the top 
    endInsertRows(); 
} 
0

对于显示,您可以尝试delegates,如链接中所述(我还没有尝试过这个例子)。如果您可以添加您的观察结果,它将有助于社区。

3

有两件事你需要做。首先是将调用调整为beginInsertRows。因为我们在这里告诉模型,我们正在添加行,他们会去哪里以及我们添加了多少。下面是该方法的描述:

无效化QAbstractItemModel :: beginInsertRows(常量QModelIndex &父, INT第一,INT去年)

所以你的情况,因为你要在第一添加一行索引,并且只有一行,我们将0作为第一个项目的索引,0作为我们添加的最后一个项目的索引(因为当然,我们只添加一个项目)。

beginInsertRows(modelIndex(), 0, 0); 

接下来我们必须提供该项目的数据。我假设'list'是一个QList(如果不是,它可能类似)。所以我们想调用'insert'方法。

list.insert(0, item); 

而且应该是这样。