Search code examples
qtqtreeview

Assigning Icons to items in QTreeView


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?


Solution

  • 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