简体   繁体   中英

Only display certain files in QFileDialog

Here's an example code I've written:

from PyQt5.QtWidgets import (QApplication, QMainWindow, QFileDialog)
import sys


class Window(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        dialog = QFileDialog()
        dialog.exec()

app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()

When I run it, I get the following: 在此处输入图片说明

These are all the files in my directory. I would like to filter out files that don't have the word 'spam' in their title, so that when I run the file, the only files that are displayed are 'spam.txt', 'spam_eggs_and_spam.txt', and 'spam_eggs_tomato_and_spam.txt'.

You could simply add a filter like this:

dialog = QFileDialog()
dialog.setNameFilter("Text Spam Files (*spam*.txt)")
dialog.exec()

But it can be overriden if the user types *.* in the filename field.

A better way to do this would be to implement your own QSortFilterProxyModel , here is my attempt:

from PyQt5.QtWidgets import (QApplication, QMainWindow, QFileDialog)
from PyQt5.QtCore import QSortFilterProxyModel, QModelIndex
import sys


class FileFilterProxyModel(QSortFilterProxyModel):
    def __init__(self, parent=None):
        super(QSortFilterProxyModel, self).__init__(parent)

    def filterAcceptsRow(self, source_row: int, source_parent: QModelIndex) -> bool:
        source_model = self.sourceModel()
        index0 = source_model.index(source_row, 0, source_parent)
        if source_model.isDir(index0):
            return True
        return 'spam' in source_model.fileName(index0).lower()


class Window(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        dialog = QFileDialog()
        dialog.setOption(QFileDialog.DontUseNativeDialog)
        dialog.setProxyModel(FileFilterProxyModel())
        dialog.setNameFilter("Text Files (*.txt)")
        dialog.exec()


app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()

要仅显示其中带有“垃圾邮件”字样的文件,您可以添加:

dialog.setNameFilters(["*spam*"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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