【问题标题】:Crash when combining QFileSystemModel with QSortFilterProxyModel将 QFileSystemModel 与 QSortFilterProxyModel 组合时崩溃
【发布时间】:2020-04-28 20:50:58
【问题描述】:

我有 QfileSysteModel 和 QSortFilterProxyModel。当我尝试调用QfileSysteModel.filePath 来获取文件的当前索引时,错误发生为core Dump。这是一段代码

    le = QLineEdit()
    lv = QListView()

    file_model = QFileSystemModel()
    file_model.setRootPath(QtCore.QDir.rootPath())

    proxy_model = QSortFilterProxyModel(
        recursiveFilteringEnabled=True,
        filterRole=QtWidgets.QFileSystemModel.FileNameRole)
    proxy_model.setSourceModel(file_model)
    lv.setModel(self.proxy_model)

它运行良好,但是当我尝试调用 QFileSystemModel Core Dumps 的任何方法时。例如

filepath  = file_model.filePath(lv.currentIndex())

如何使用QfileSystemModel的任何方法

from PyQt5 import QtCore, QtGui, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        le = QtWidgets.QLineEdit()
        self.lv = QtWidgets.QListView()

        self.file_model = QtWidgets.QFileSystemModel()
        self.file_model.setRootPath(QtCore.QDir.rootPath())

        self.proxy_model = QtCore.QSortFilterProxyModel(
            recursiveFilteringEnabled=True,
            filterRole=QtWidgets.QFileSystemModel.FileNameRole)
        self.proxy_model.setSourceModel(self.file_model)
        self.lv.setModel(self.proxy_model)
        root_index = self.file_model.index(QtCore.QDir.rootPath())
        proxy_index = self.proxy_model.mapFromSource(root_index)
        self.lv.setRootIndex(proxy_index)
        self.lv.doubleClicked.connect(self.navigate)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(le)
        lay.addWidget(self.lv)


    def navigate(self):

        # Get the path of file or folder
        filepath  = self.file_model.filePath(self.lv.currentIndex())
        print(filepath)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

【问题讨论】:

  • 什么是self.files? ....
  • 抱歉这个错误。我修改了它,它是file_model。我将尝试提供代码的快捷方式,因为它是长代码
  • 我没有收到任何错误,如果您需要帮助,您必须提供 MRE。
  • MRE 必须很小,但最重要的是它必须是可重现的。

标签: python pyqt pyqt5 qfilesystemmodel


【解决方案1】:

使用代理模型时,代理的ModelIndex 与源模型中的索引不同。使用mapToSource() 将代理模型转换为源模型。

在你的情况下,它可能看起来像这样:

# alternative one: do not reference proxy_model directly
filepath = file_model.filePath(lv.model().mapToSource(lv.currentIndex()))
# alternative two:
filepath = file_model.filePath(self.proxy_model.mapToSource(lv.currentIndex()))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多