TreeView : How could I show directories first?



  • Hi guys :

    I wonder if there is a way to sort "TreeView" to show Directories first , then files?

    Thanks.
    MSD.



  • I assume that you are using QFileSystemModel?
    As far as I know / can tell it's not possible to just flick a switch. However, you can still get this going by implementing a custom sort-filter model (subclassing QSortFilterProxyModel). You should be able to overwrite QSortFilterProxyModel::lessThan() to implement the behavior your are looking for. You would basically compare the isDir() attribute that you can retrieve from the underlying QFileSystemModel.

    Something like this comes to mind (untested!):

    bool MySortFilterModel::lessThan(const QModelIndex& left, const QModelIndex& right) const
    {
    	QFileSystemModel* model = qobject_cast<QFileSystemModel*>(sourceModel());
    	if (!model) {
    		qFatal("Shit hit the fan");
    		return true;
    	}
    	
    	if (!model->fileInfo(left).isDir() && model->fileInfo(right).isDir()) {
    	    return false;
    	}
    
    	return true;
    }
    

    This is just a - most likely not even compiling - example showing the general idea behind this. You'd have to also take the sorting order into account by checking QSortFilterProxyModel::sortOrder().

    I hope that helps somehow.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.