Question

I have addFile function in my TableModel class which inserts a new record at the end.

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();
}

This function works fine but instead of appending record at the end I would like to insert it at the top. Any pointers on how to update my existing function ?

I have already tried some combinations but there is no Luck.

Was it helpful?

Solution 3

Thanks to everyone for replying. I have found the solution by my own:

In case if anyone is interested

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();
}

OTHER TIPS

There are two things that you need to do. First is to adjust the call to beginInsertRows. Because it is here that we are telling the model that we are adding rows, where they will go, and how many we are adding. Here is the method description:

void QAbstractItemModel::beginInsertRows ( const QModelIndex & parent, int first, int last )

So in your case since you want to add a row at the first index, and only one row, we pass 0 as the index of the first item, and 0 which is the index of the last item we are adding (because of course we are only adding one item).

beginInsertRows(modelIndex(), 0, 0);

Next we have to provide the data for the item. I assume that 'list' is a QList (if not it is probably similar). So we want to call the 'insert' method.

list.insert(0, item);

And that should be it.

For display you can try delegates as explained in the link (I haven't tried the example though). It will help the community if you can add your observations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top