I created a window like this The link! and when I select a directory I would like to select all items in the right Qlist, and when I change to a different directory, I would deselect the items in the previous directory and select all items in my current directory.
How can I approach this?
To select and deselect all items you must use selectAll()
and clearSelection()
, respectively. But the selection must be after the view that is updated and for this the layoutChanged
signal is used, also the selection mode must be set to QAbstractItemView::MultiSelection
.
import sys
from PyQt5 import QtCore, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super(Widget, self).__init__(*args, **kwargs)
hlay = QtWidgets.QHBoxLayout(self)
self.treeview = QtWidgets.QTreeView()
self.listview = QtWidgets.QListView()
hlay.addWidget(self.treeview)
hlay.addWidget(self.listview)
path = QtCore.QDir.rootPath()
self.dirModel = QtWidgets.QFileSystemModel(self)
self.dirModel.setRootPath(QtCore.QDir.rootPath())
self.dirModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllDirs)
self.fileModel = QtWidgets.QFileSystemModel(self)
self.fileModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
self.treeview.setModel(self.dirModel)
self.listview.setModel(self.fileModel)
self.treeview.setRootIndex(self.dirModel.index(path))
self.listview.setRootIndex(self.fileModel.index(path))
self.listview.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
self.treeview.clicked.connect(self.on_clicked)
self.fileModel.layoutChanged.connect(self.on_layoutChanged)
@QtCore.pyqtSlot(QtCore.QModelIndex)
def on_clicked(self, index):
self.listview.clearSelection()
path = self.dirModel.fileInfo(index).absoluteFilePath()
self.listview.setRootIndex(self.fileModel.setRootPath(path))
@QtCore.pyqtSlot()
def on_layoutChanged(self):
self.listview.selectAll()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())