python - 选择 QListView 中的所有项目并在目录更改时取消选择所有项目

标签 python pyqt pyqt5 qlistview qfilesystemmodel

我创建了一个这样的窗口 The link !当我选择一个目录时,我想选择正确的 Qlist 中的所有项目,而当我切换到另一个目录时,我会取消选择前一个目录中的项目并选择我当前目录中的所有项目。

我该如何解决这个问题?

最佳答案

要选择和取消选择所有项目,您必须分别使用 selectAll()clearSelection()。但是选择必须在更新的 View 之后进行,为此使用 layoutChanged 信号,选择模式也必须设置为 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_())

关于python - 选择 QListView 中的所有项目并在目录更改时取消选择所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53601248/

相关文章:

python - Python 中 txt 文件的数组/列表

python - Qt - 暂时禁用所有事件或窗口功能?

python - 如何将QChart坐标映射到QChartView点?

python - pyqt dropEvent 不会触发

python - PyQt [QTreeWidget] : How to add Radiobutton for items?

python - 如何在 PyQt/PySide 中将项目添加到 QComboBox

python - 基于多个条件创建列的简洁方法

python - 如何并行化复杂的 for 循环

python - 如何卸载(重新加载)Python 模块?

python - QGraphicsItem 移动后没有留在原处