QFileSystemModel排序DirsFirst

时间:2012-05-28 18:59:19

标签: qt sorting qfilesystemmodel

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

2 个答案:

答案 0 :(得分:3)

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

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);
}

答案 1 :(得分:1)

据我所知,你不能(在Qt4中)。

默认排序顺序(通过“名称”列)或按大小排序的行为类似QDir::DirsFirst(或DirsLast,如果顺序相反),但按时间或类型排序不处理目录与普通文件不同。

QFileSystemModel没有公开用于更改排序顺序的API,我认为没有机会在QFileSystemModel代码中影响它。

(我在当前的Qt5文档中没有看到任何表明这已经改变的内容,但这些都不是最终的,我没有仔细看过。)

相关问题