[英]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'. 我想过滤掉标题中没有单词“ spam”的文件,以便在我运行该文件时,仅显示“ spam.txt”,“ spam_eggs_and_spam.txt”和“ 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: 更好的方法是实现自己的QSortFilterProxyModel
,这是我的尝试:
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*"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.