QFileDialog查看文件夹和文件,但仅选择文件夹吗? [英] QFileDialog view folders and files but select folders only?

查看:756
本文介绍了QFileDialog查看文件夹和文件,但仅选择文件夹吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating my own custom file dialog using the following code:

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

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

The behaviour that i'm interested in is for the user to be able to view both files and folders, but select folders only. (making files unselectable). Is that possible?

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

Note: Using the DirectoryOnly option is not good for me since it doesn't allow you to view files, just folders.

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

Edit (extra code that i forgot to add which responsible for being able to select multiple folders instead of just one):

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)

推荐答案

要防止选择文件,可以安装代理模型,该模型处理文件视图中项目的标志:

To prevent files being selected, you can install a proxy model which manipulates the flags for items in the file-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()

这篇关于QFileDialog查看文件夹和文件,但仅选择文件夹吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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