PyQt QFileDialog-多目录选择 [英] PyQt QFileDialog - Multiple Directory Selection

查看:430
本文介绍了PyQt QFileDialog-多目录选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个QFileDialog,允许用户选择多个目录.

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).

这是在Windows 7上

This is on Windows 7

代码:

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_())

因此,在进行了更多操作之后,如果我在文件对话框中选择详细信息视图",则多选有效.但是,如果我选择列表视图",则它不起作用.知道为什么吗?

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?

推荐答案

常见问题解答中的示例代码并不可靠,因为它假定对话框中只有一个QListView和一个QTreeView.当有多个直接子对象时,findChild的行为是不确定的:因此,它曾经发挥作用可能只是纯粹的运气.

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.

更可靠的解决方案是在其模型类型为QFileSystemModel的任何视图上重置选择模式:

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)

这篇关于PyQt QFileDialog-多目录选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆