2016-07-27 155 views
1

我使用下面的代码创建自己的自定义文件对话框: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) 
+0

你已经发布的代码做你说你想要什么(即用户可以查看文件和显示目录,但只选择迪尔斯)。所以也许你需要更清楚地解释你想达到的目标。 – ekhumoro

+0

不是真的..上面的代码可以让你选择文件。 – YaronGh

+0

对我而言,只有在选择目录时才会启用“选择”按钮。可以*选择*文件,但不能选择它们(因为按钮被禁用)。 – ekhumoro

回答

2

为了防止被选定的文件,你可以安装一个代理模型,操纵标志在文件视图中的项目:

class ProxyModel(QtGui.QIdentityProxyModel): 
    def flags(self, index): 
     flags = super(ProxyModel, self).flags(index) 
     if not self.sourceModel().isDir(index): 
      flags &= ~QtCore.Qt.ItemIsSelectable 
     return flags 


# keep a reference somewhere to prevent core-dumps on exit 
self._proxy = ProxyModel(self) 

file_dialog.setProxyModel(self._proxy) 
+0

好的非常感谢!我不知道是否应该为此打开一个新问题(请告诉我) - 但是,我可以对上面的代码进行快速修改,以便能够选择文件夹和文件? – YaronGh

+1

@YaronGh。 'file_dialog.setProxyModel(无)'。 – ekhumoro

+0

如果我这样做,它会返回所选文件+该文件夹中的所有其他文件 – YaronGh