5

I have a class inheriting from QTreeView. I need to assign icons to different types of files and directories. There is this solution given from this question:

QVariant MyQFileSystemModel::data( const QModelIndex& index, int role ) const {
    if( role == Qt::DecorationRole )
    {
        QFileInfo info = MyQFileSystemModel::fileInfo(index);

        if(info.isFile())
        {
            if(info.suffix() == "dat")
                return QPixmap(":/icons/File_Icon.png");//I pick the icon depending on the extension
            else if(info.suffix() == "mcr")
                return QPixmap(":/icons/Region_Icon.png");
        }
    }
    return QFileSystemModel::data(index, role);
}

My class does not inherit from QFileSystemModel but rather compose it in, which means I cannot overide the function data(). From the above, how will the icons show up? Is it by just calling data() in a constructor?

Community
  • 1
  • 1
Amani
  • 16,245
  • 29
  • 103
  • 153

2 Answers2

4

You need to add a model to your tree with a root node:

QStandardItemModel* model = new QStandardItemModel;
QStandardItem * rootNode = model->invisibleRootItem();
this->setModel(model); //Your class inherts from QTreeView

and then to add an item with an icon :

QStandardItem* item = new QStandardItem("myItem")
item->setIcon(QIcon("icon.jpg"));
rootNode->appendRow(item);

you may have something like this : http://hpics.li/e9dc5dd

Amott
  • 191
  • 9
  • I already have QFileSystemModel composed in, can it (QFileSystemModel) be used for that purpose? If yes, how? – Amani Jul 11 '16 at 13:52
  • To be honest I don't know, I used a lot QTreeView with QStandardItemModel but I never used QFileSystemModel so I don't want to tell you something that I'm not sure – Amott Jul 11 '16 at 14:12
1

I want to add that if you use QStandardItem in your custom model subclassing QAbstractItemModel, you need to add role == Qt::DecorationRole in your reimplemented data() function, so that the icon can display on the view.

Something is like:

QVariant SnapshotTreeModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (role == Qt::DisplayRole){
        ....
        return item->text();
    }else if (role == Qt::DecorationRole){
        QStandardItem *item = static_cast<QStandardItem *>(index.internalPointer());
        return item->icon();
    }

    return QVariant();
}
oscarz
  • 1,184
  • 11
  • 19