Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

python - PyQt QFileDialog - Multiple Directory Selection

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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((QListView, QTreeView)):
    if isinstance(view.model(), QFileSystemModel):
        view.setSelectionMode(QAbstractItemView.ExtendedSelection)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...