How to add custom row in QFileSystemModel?

1.6k views Asked by At

I am using QFileSystemModel to represent file structure through the QTreView. Everything works fine, but I need to add an additional row at some level of the tree. For example for now is:

-root

--row1

--row2

--row3

All these rows mapping folders/files from file system. I need:

-root

--row1

--row2

--row3

--custom row

So custom row is not representing any data from file system. I just need to add here my own data. I have read a lot of stuff from the internet and people advice to use proxy model and reimplement rowCount(), data() and flags() functions. I tried to do that(used class derived from QSortFilterProxyModel), but I never get my row in data() and flags() functions. Seems like it takes count from source model.

QVariant AddonFilterModel::data (const QModelIndex & index, int role) const
{
    if(role == Qt::DisplayRole && index.row() == FilterModel::rowCount(index))
    {
        return QString("Add-Ons");
    }

    return FilterModel::data(index, role);
}

Qt::ItemFlags AddonFilterModel::flags(const QModelIndex & index) const
{
    if (!index.isValid())
        return 0;

    if (index.row() == FilterModel::rowCount(index))
    {
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
    }

    return FilterModel::flags(index);
}

int AddonFilterModel::rowCount(const QModelIndex &parent) const
{
    int count = FilterModel::rowCount(parent);

    if(parent == this->getRootIndex())
    {
        return count+1;
    }
    return count;
}

Using class derived from QAbstractProxyModel is not acceptable because I need filtering functions of QSortFilterProxyModel().

Also I have tried to reimplement rowCount() of QFileSystemModel to make changes directly in model but I am getting "array out of range" error from QT code.

I have tried insertRow() method but it is not working. I think because QFileSystemModel is read only.

Did anyone face this problem? Any ideas?

1

There are 1 answers

0
Peter G Holm On

Late answer. You have to subclass Qabstractitemmodel.