繁体   English   中英

QFileDialog 仅过滤未知文件类型

[英]QFileDialog filter unknown file types only

QFileDialog.getOpenFileNames(self, 'Choose File', self.filelocation, filter="?" (*)")

当我尝试使用 QFileDialog 选择文件时,它会显示所有文件 - 但我只想过滤未知的文件类型,如下图所示。 是否可以? 或者如何禁用 .txt 文件? 在此处输入图片说明

看起来您必须为此使用代理模型,因为名称过滤器使用通配符匹配(它不支持像!(*.*)这样的否定模式),并且mime-filters似乎无法识别任何类型“未知”文件类型。

下面是一个使用QSortFilterProxyModel的工作解决方案。 filterAcceptsRow的逻辑只允许通过所有目录和任何没有点的文件,但您可以根据需要轻松调整它。 (要获得有关文件的更多详细信息,您可以使用例如info = model.fileInfo(index)来获取QFileInfo对象)。

from PyQt5 import QtCore, QtGui, QtWidgets

class ProxyModel(QtCore.QSortFilterProxyModel):
    def filterAcceptsRow(self, source_row, source_parent):
        model = self.sourceModel()
        index = model.index(source_row, 0, source_parent)
        return model.isDir(index) or '.' not in model.fileName(index)

    def sort(self, column, order):
        self.sourceModel().sort(column, order)

app = QtWidgets.QApplication(['Test'])

dialog = QtWidgets.QFileDialog()
dialog.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
dialog.setWindowTitle('Choose Files')
dialog.setProxyModel(ProxyModel())
dialog.exec()

暂无
暂无

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

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