PyQt QFileDialog - Multiple Directory Selection

蓝咒 提交于 2019-11-28 05:04:58

问题


I am trying to create a QFileDialog that allows the user to select multiple directories.

Following the discussion here and the faq here, but I'm not sure what I'm doing wrong. I get a file dialog, but it still only lets me select a single directory (folder).

This is on Windows 7

Code:

class FileDialog(QtGui.QFileDialog):
        def __init__(self, *args):
            QtGui.QFileDialog.__init__(self, *args)
            self.setOption(self.DontUseNativeDialog, True)
            self.setFileMode(self.DirectoryOnly)

            self.tree = self.findChild(QtGui.QTreeView)
            self.tree.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

            self.list = self.findChild(QtGui.QListView)
            self.list.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    ex = FileDialog()
    ex.show()
    sys.exit(app.exec_())

Edit:

So after playing around with this some more, if I select "Detail View" in the file dialog, multiselection works. However, if I select "List View" it does not work. Any idea why?


回答1:


The example code from the FAQ is not robust, because it assumes the dialog only has one QListView and one QTreeView. The behaviour of findChild is indeterminate when there are several direct child objects: so it was probably just pure luck that it ever worked.

A more robust solution would be to reset the selection mode on any view for which the type of its model is a QFileSystemModel:

for view in self.findChildren((QtGui.QListView, QtGui.QTreeView)):
    if isinstance(view.model(), QtGui.QFileSystemModel):
        view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)


来源:https://stackoverflow.com/questions/28544425/pyqt-qfiledialog-multiple-directory-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!