Panupat
Panupat

Reputation: 462

QTreeView QFileSystemModel - limit expandable to only root

I'm using QTreeView and QFileSystemModel. I want only the root to be expandable, showing 1 level of subdirectory and that's it, the subdirectories should only be selectable but not expandable. Any guidance how I can archive this please?

Thank you.

Upvotes: 1

Views: 616

Answers (1)

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

As previously suggested, you can create a proxy model to modify the model's behavior:

class Proxy : public QSortFilterProxyModel {
public:
  static int indexLevel(QModelIndex index) {
    int level = 0;
    while(index.parent().isValid()) {
      level++;
      index = index.parent();
    }
    return level;
  }

  int rowCount(const QModelIndex& parent) const {
    if (indexLevel(parent) > 0) {
      return 0;
    }
    return QSortFilterProxyModel::rowCount(parent);
  }

  bool hasChildren(const QModelIndex& parent) const {
    if (indexLevel(parent) > 0) {
      return false;
    }
    return QSortFilterProxyModel::hasChildren(parent);
  }
};

//...
QFileSystemModel model;
model.setRootPath(QString());
Proxy proxy;
proxy.setSourceModel(&model);
QTreeView view;
view.setModel(&proxy);
view.show();

Upvotes: 2

Related Questions