【问题标题】:Select all items in QListView and deselect all when directory is changed选择 QListView 中的所有项目,并在更改目录时取消选择所有项目
【发布时间】:2019-06-12 13:34:25
【问题描述】:

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

我该如何处理?

【问题讨论】:

    标签: python pyqt pyqt5 qlistview qfilesystemmodel


    【解决方案1】:

    要选择和取消选择所有项目,您必须分别使用selectAll()clearSelection()。但选择必须在更新的视图之后,为此使用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_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      相关资源
      最近更新 更多