When you execute your code you get the following message:
QAbstractItemView::setRootIndex failed : index must be from the currently set model
And that message gives us an important clue, a QModelIndex belongs to a model so although it has the same data from another QModelIndex of another model they are not the same.
There are 2 possible solutions:
import os
from PyQt5 import QtCore, QtGui, QtWidgets
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
model = QtWidgets.QFileSystemModel()
model.setRootPath(QtCore.QDir.rootPath())
treeView = QtWidgets.QTreeView()
treeView.setModel(model)
treeView.setRootIndex(model.index(QtCore.QDir.homePath()))
listView = QtWidgets.QListView()
listView.setModel(model)
listView.setRootIndex(model.index(QtCore.QDir.homePath()))
treeView.clicked.connect(listView.setRootIndex)
w = QtWidgets.QWidget()
hlay = QtWidgets.QHBoxLayout(w)
hlay.addWidget(treeView)
hlay.addWidget(listView)
w.show()
sys.exit(app.exec_())
- Obtain the QModelIndex of the other model using the QModelIndex information of the initial model:
import os
from PyQt5 import QtCore, QtGui, QtWidgets
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
dirModel = QtWidgets.QFileSystemModel()
dirModel.setRootPath(QtCore.QDir.rootPath())
dirModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Dirs)
listModel = QtWidgets.QFileSystemModel()
listModel.setRootPath(QtCore.QDir.rootPath())
treeView = QtWidgets.QTreeView()
treeView.setModel(dirModel)
treeView.setRootIndex(dirModel.index(QtCore.QDir.homePath()))
listView = QtWidgets.QListView()
listView.setModel(listModel)
listView.setRootIndex(listModel.index(QtCore.QDir.homePath()))
treeView.clicked.connect(
lambda ix: listView.setRootIndex(
listModel.index(ix.data(QtWidgets.QFileSystemModel.FilePathRole))
)
)
w = QtWidgets.QWidget()
hlay = QtWidgets.QHBoxLayout(w)
hlay.addWidget(treeView)
hlay.addWidget(listView)
w.show()
sys.exit(app.exec_())