Reputation: 10573
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'.
Upvotes: 0
Views: 2509
Reputation: 15209
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_()
Upvotes: 2
Reputation: 86
To only show files with the word 'spam' in them you can add:
dialog.setNameFilters(["*spam*"])
Upvotes: 1