1

Does anybody know how to implement/realize a QTreeView with different colors for subgroups of the QTreeView items?
Something like:

1

Does anybody has done something like that and could give me a link to an tutorial or how to, or sample code would also be good. Currently I have absolutely no idea how to build this.

I'm working with Qt 5.1.1 and using the QTreeView with the QFileSystemModel and the QItemSelectionModel.

I also thought of :
m_TreeView->setStyleSheet(...)
but this only sets the style for the whole treeView or only for the selected ones.

Any suggestions? Thanks a lot for your help!

Prophet
  • 32,350
  • 22
  • 54
  • 79
user1911091
  • 1,219
  • 2
  • 14
  • 32
  • You could try to look at `QAbstractItemModel::data()` with `Qt::BackgroundRole` as a second argument. – vahancho Nov 27 '13 at 20:04

1 Answers1

4

There's Qt::BackgroundRole which can be used to return a QColor to be used by the view to paint an index' background.

As you use an existing item model class (QFileSystemModel), it would be easiest to put a proxy model on top of the file system model just doing the colorization.

Using QIdentityProxyModel:

class ColorizeProxyModel : public QIdentityProxyModel {
    Q_OBJECT
public:
    explicit ColorizeProxyModel(QObject *parent = 0) : QIdentityProxyModel(parent) {}

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const {
        if (role != Qt::BackgroundRole) 
            return QIdentityProxyModel::data(index, role);

        ... find out color for index 
        return color;
    }
};

To use it:

QFileSystemModel *fsModel = new QFileSystemModel(this);
ColorizeProxyModel *colorProxy = new ColorizeProxyModel(this);
colorProxy->setSourceModel(fsModel);
treeView->setModel(colorProxy);

If you need anything more fancy, (like special shapes etc.), you'd need your own item delegate with custom painting (see QStyledItemDelegate).

Frank Osterfeld
  • 24,815
  • 5
  • 58
  • 70