python - QFileDialog 查看文件夹和文件但仅选择文件夹?

标签 python qt pyqt qfiledialog

我正在使用以下代码创建自己的自定义文件对话框:

file_dialog = QtGui.QFileDialog()
file_dialog.setFileMode(QtGui.QFileDialog.Directory)
file_dialog.setViewMode(QtGui.QFileDialog.Detail)
file_dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)

我感兴趣的行为是用户能够查看文件和文件夹,但仅选择文件夹。 (使文件不可选择)。那可能吗?

注意: 使用 DirectoryOnly 选项对我来说不好,因为它不允许您查看文件,而只能查看文件夹。

编辑(我忘记添加的额外代码负责选择多个文件夹而不是仅一个):

file_view = file_dialog.findChild(QtGui.QListView, 'listView')
if file_view:
    file_view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
f_tree_view = file_dialog.findChild(QtGui.QTreeView)
if f_tree_view:
    f_tree_view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

最佳答案

为了防止选择文件,您可以安装一个代理模型来操纵文件 View 中项目的标志:

dialog = QFileDialog()
dialog.setFileMode(QFileDialog.Directory)
dialog.setOption(QFileDialog.DontUseNativeDialog, True)

class ProxyModel(QIdentityProxyModel):
    def flags(self, index):
        flags = super(ProxyModel, self).flags(index)
        if not self.sourceModel().isDir(index):
            flags &= ~Qt.ItemIsSelectable
            # or disable all files
            # flags &= ~Qt.ItemIsEnabled
        return flags

proxy = ProxyModel(dialog)
dialog.setProxyModel(proxy)

dialog.exec()

关于python - QFileDialog 查看文件夹和文件但仅选择文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38624245/

相关文章:

python - 制作允许 0.1 + 0.2 = 0.3 的 testfunc

Qt QMdiArea 背景上的图像

python - PyQt:可编辑的 QTabWidget 选项卡文本

python - 用 QTableWidget 显示一个巨大的表

python 多索引赋值

python - 使用 python-gstreamer 指定声卡

python - 代码无法正常工作(Python 3.x.x)

c# - 关于使用带有 C# Gui 的 QT 后端的好资源

windows - 为什么 QString::localeAwareCompare() 不能正常工作

python - 使用 Pynsist 和 PyQt 构建的 GUI : Import Error 'sip'