The documentation for QFileDialog.getOpenFileName does not provide any clue on how to filter only executables using a const QString &filter = QString()
. Here’s the code for my action using PyQt5:
JavaScript
x
26
26
1
from PyQt5.QtWidgets import QAction, QFileDialog
2
from PyQt5.QtCore import QDir
3
from os import path
4
5
6
class OpenSourcePortAction(QAction):
7
8
def __init__(self, widget, setSourcePort, config, saveSourcePortPath):
9
super().__init__('&Open Source Port', widget)
10
self.widget = widget
11
self.setShortcut('Ctrl+O')
12
self.setStatusTip('Select a source port')
13
self.triggered.connect(self._open)
14
self.setSourcePort = setSourcePort
15
self.config = config
16
self.saveSourcePortPath = saveSourcePortPath
17
18
def _open(self):
19
options = QFileDialog.Options()
20
options |= QFileDialog.DontUseNativeDialog
21
fileName, _ = QFileDialog.getOpenFileName(
22
self.widget, "Select a source port", self.config.get("sourcePortDir"), "Source Ports (gzdoom zandronum)", options=options)
23
if fileName:
24
self.saveSourcePortPath(fileName)
25
self.setSourcePort(fileName)
26
On linux, naturally, I have no file extensions for executables, but I need to filter .exe extensions on windows (Which I intend to provide a version for). Also, there’s no overloaded method that allows QDir::Executable. How can I use QFileDialog.getOpenFileName
while filtering only executables, no matter which platform it’s running on?
Advertisement
Answer
If you want a more personalized filter then you have to use a proxyModel but for this you cannot use the getOpenFileName method since the QFileDialog instance is not easily accessible since it is a static method.
JavaScript
1
34
34
1
class ExecutableFilterModel(QSortFilterProxyModel):
2
def filterAcceptsRow(self, source_row, source_index):
3
if isinstance(self.sourceModel(), QFileSystemModel):
4
index = self.sourceModel().index(source_row, 0, source_index)
5
fi = self.sourceModel().fileInfo(index)
6
return fi.isDir() or fi.isExecutable()
7
return super().filterAcceptsRow(source_row, source_index)
8
9
10
class OpenSourcePortAction(QAction):
11
def __init__(self, widget, setSourcePort, config, saveSourcePortPath):
12
super().__init__("&Open Source Port", widget)
13
self.widget = widget
14
self.setShortcut("Ctrl+O")
15
self.setStatusTip("Select a source port")
16
self.triggered.connect(self._open)
17
self.setSourcePort = setSourcePort
18
self.config = config
19
self.saveSourcePortPath = saveSourcePortPath
20
21
def _open(self):
22
proxy_model = ExecutableFilterModel()
23
options = QFileDialog.Options()
24
options |= QFileDialog.DontUseNativeDialog
25
dialog = QFileDialog(
26
self.widget, "Select a source port", self.config.get("sourcePortDir")
27
)
28
dialog.setOptions(options)
29
dialog.setProxyModel(proxy_model)
30
if dialog.exec_() == QDialog.Accepted:
31
filename = dialog.selectedUrls()[0].toLocalFile()
32
self.saveSourcePortPath(fileName)
33
self.setSourcePort(fileName)
34