简体   繁体   English

QFileDialog中的多个文件和文件夹选择?

[英]Multiple files AND folder selection in a QFileDialog?

I am using pyQt4 and want to have a Browse button in my GUI which opens up a Dialog box allowing user to select multiple files AND folders. 我正在使用pyQt4,并希望在我的GUI中有一个“浏览”按钮,打开一个对话框,允许用户选择多个文件文件夹。 I have researched quite a bit but din't find any way to be able to do this. 我已经研究了很多但是没有找到任何方法可以做到这一点。

The QFileDialog.getOpenFileNames() only allows me to choose files and QFileDialog.getExistingDirectory() only allows to choose directories. QFileDialog.getOpenFileNames()只允许我选择文件,QFileDialog.getExistingDirectory()只允许选择目录。

Is there any way I can somehow combine their functionality. 有什么方法可以以某种方式结合他们的功能。 Ideally I would like to use the nativeDialogs but that doesn't seem to be possible. 理想情况下,我想使用nativeDialogs但似乎不可能。 As a result I am willing to compromise on the looks. 因此,我愿意在外观上妥协。 Is there any way I can implement the said? 有什么办法可以实现上述说法吗?

The same question has been asked here as well but the answer is in c++. 这里也提出了同样的问题,但答案是在c ++中。 I need a python implementation. 我需要一个python实现。 Allow user to select a file or a folder in QFileDialog 允许用户在QFileDialog中选择文件或文件夹

Here's a hack that should work for you: Create a subclass of QFileDialog that disconnects the "Open" button and reconnects it to a customized function. 这是一个应该适合您的hack:创建QFileDialog的子类,断开“打开”按钮并将其重新连接到自定义函数。 It's not guaranteed to work across different versions of Qt, though, since it relies on being able to find specific sub-widgets that may be reconfigured at some point. 但是,不能保证在不同版本的Qt中工作,因为它依赖于能够找到可能在某些时候重新配置的特定子窗口小部件。

class FileDialog(QtGui.QFileDialog):
    def __init__(self, *args):
        QtGui.QFileDialog.__init__(self, *args)
        self.setOption(self.DontUseNativeDialog, True)
        self.setFileMode(self.ExistingFiles)
        btns = self.findChildren(QtGui.QPushButton)
        self.openBtn = [x for x in btns if 'open' in str(x.text()).lower()][0]
        self.openBtn.clicked.disconnect()
        self.openBtn.clicked.connect(self.openClicked)
        self.tree = self.findChild(QtGui.QTreeView)

    def openClicked(self):
        inds = self.tree.selectionModel().selectedIndexes()
        files = []
        for i in inds:
            if i.column() == 0:
                files.append(os.path.join(str(self.directory().absolutePath()),str(i.data().toString())))
        self.selectedFiles = files
        self.hide()

    def filesSelected(self):
        return self.selectedFiles

在Qt5中你可以简单地使用

return QtWidgets.QFileDialog.getOpenFileNames(self, title, directory, filter=filterFile)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM