简体   繁体   English

QFileDialog 查看文件夹和文件但只选择文件夹?

[英]QFileDialog view folders and files but select folders only?

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?这可能吗?

Note: Using the DirectoryOnly option is not good for me since it doesn't allow you to view files, just folders.注意:使用DirectoryOnly选项对我不利,因为它不允许您查看文件,只能查看文件夹。

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

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

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