How to create a file dialog that returns file paths for both selected files AND directories?

守給你的承諾、 提交于 2021-02-08 06:34:24

问题


I'm trying to use QFileDialog to get a list of the paths of selected folders AND directories.

I know how to do one or the other using QFileDialog.getOpenFileNames and QFileDialog.getExistingDirectory, but not both at the same time.

The C++ docs and other questions elsewhere didn't seem to help me no matter how much I googled.

I am using PyQt5 5.14.2 and Python 3.8.2 on Windows.

Edit: I've managed to conjure up the following solution not using the native Windows dialog and it works but seems 'hacky'. Can anyone think of a better solution?

from PyQt5 import QtWidgets


main_window = QtWidgets.QApplication([])

dlg = QtWidgets.QFileDialog()
dlg.setFileMode(QtWidgets.QFileDialog.Directory)
dlg.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True)

_list = dlg.findChild(QtWidgets.QListView, 'listView')
if _list:
    _list.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)

tree = dlg.findChild(QtWidgets.QTreeView, 'treeView')
if tree:
    tree.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)

selected = None

if dlg.exec():
    selected = dlg.selectedFiles()

print(selected)

来源:https://stackoverflow.com/questions/61345234/how-to-create-a-file-dialog-that-returns-file-paths-for-both-selected-files-and

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