4

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Sally
  • 87
  • 2
  • 10

2 Answers2

5

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
1

This only requires a few lines, and the only variable you need is the one that references your QListView.

Knowing when the directory is changed is probably the least of your problems and handled in a way you're already happy with.

Let's say your QListView object is called list_view

Upon clicking on/changing your directory, run these lines:

list_view.clearSelection()
list_view.model().layoutChanged.emit()

And that's it. That will deselect all items in your QListView and update the view to show that nothing is highlighted.

NL23codes
  • 1,181
  • 1
  • 14
  • 31