首页 > 解决方案 > QFileSystemModel 和 Listview 列出目录

问题描述

我在使用 QFileSystemModel 和 Listview (qml) 时遇到问题。我想使用 2 个列表视图: - 一个列出目录的目录 - 一个列出在第一个视图中选择的目录中可用的文件

起初,我试图在列表视图中列出目录,但似乎 rootIndex 设置不正确,因为只显示“/”项:

在我的示例代码下面:

主.cpp:

QFileSystemModel *lDirModel = new QFileSystemModel();
QDir lDir = QDir("/home/toto");
lDirModel->setRootPath("/home/toto");
lDirModel->setFilter(QDir::AllEntries | QDir::AllDirs);
qml_engine->rootContext()->setContextProperty("mediaModel", lDirModel);
qml_engine->rootContext()->setContextProperty("mediaRootModel", lDirModel->index("/home/toto"));

媒体.qml

DelegateModel {
    id: visualModel
    model: mediaModel
    rootIndex: mediaRootModel
    delegate: Rectangle {
        color: "red"
        height: 40
        width: 500
        Text { text: "Name: " + filePath}
    }

}
ListView {
    anchors.fill: parent
    clip: true
    model: visualModel

}

我还使用 TreeView (qml) 对其进行了测试,即使不考虑 rootIndex 也“有效”(它从“/”开始)

问题似乎出在 ListView 中的 rootIndex 定义上。我不知道我错在哪里。通常,它必须工作。

我已阅读http://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html但该示例适用于 QAbstractListModel 而不是 QAbstractItemModel (QFileSystemModel 继承)

你知道我错在哪里吗?

谢谢您的帮助。

编辑:奇怪的是,使用 qlistview,它可以工作并显示 $HOME 内容:

QFileSystemModel *lModel = new QFileSystemModel();
QModelIndex lIndex = lModel->setRootPath("/home/toto");
_ui->recordsListView->setModel(lModel);
_ui->recordsListView->setRootIndex(lIndex);

有人可以帮忙吗?

标签: qtlistviewqmlqfilesystemmodel

解决方案


推荐阅读