QFileSystemModel 排序 DirsFirst

Yas*_*azk 2 sorting qt qfilesystemmodel

你如何像在 QDirModel 中那样使用 QDir::DirsFirst 对 QFileSystemModel 进行排序?QFileSystemModel 没有setSorting方法。

x61*_*610 6

也许有人会需要这个。正如 Kuba Ober 在评论中提到的那样,我首先使用 QSortFilterProxyModel 为 QFileSystemModel 实现了目录排序。可能还不完美,但仍然是正确的方向。

bool MySortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
    // If sorting by file names column
    if (sortColumn() == 0) {
        QFileSystemModel *fsm = qobject_cast<QFileSystemModel*>(sourceModel());
        bool asc = sortOrder() == Qt::AscendingOrder ? true : false;

        QFileInfo leftFileInfo  = fsm->fileInfo(left);
        QFileInfo rightFileInfo = fsm->fileInfo(right);


        // If DotAndDot move in the beginning
        if (sourceModel()->data(left).toString() == "..")
            return asc;
        if (sourceModel()->data(right).toString() == "..")
            return !asc;

        // Move dirs upper
        if (!leftFileInfo.isDir() && rightFileInfo.isDir()) {
            return !asc;
        }
        if (leftFileInfo.isDir() && !rightFileInfo.isDir()) {
            return asc;
        }
    }

    return QSortFilterProxyModel::lessThan(left, right);
}
Run Code Online (Sandbox Code Playgroud)