I have QfileSysteModel and QSortFilterProxyModel. When I try to call QfileSysteModel.filePath
to get the current index of the file Error occurs as core Dump
. Here is a piece of code
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)
It works well, but when I try to call any methods of the QFileSystemModel
Core Dumps. for example
filepath = file_model.filePath(lv.currentIndex())
How can I use any method of the 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_())
When working with a proxy model, the ModelIndex
of the proxy differs from the index in the source model. Use mapToSource()
to convert from proxy model to source model.
In your case, it would probably look like this:
# 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()))