[英]How to filter executables using QFileDialog? (Cross-platform solution)
QFileDialog.getOpenFileName 的文檔沒有提供有關如何使用const QString &filter = QString()
僅過濾可執行文件的任何線索。 這是我使用 PyQt5 操作的代碼:
from PyQt5.QtWidgets import QAction, QFileDialog
from PyQt5.QtCore import QDir
from os import path
class OpenSourcePortAction(QAction):
def __init__(self, widget, setSourcePort, config, saveSourcePortPath):
super().__init__('&Open Source Port', widget)
self.widget = widget
self.setShortcut('Ctrl+O')
self.setStatusTip('Select a source port')
self.triggered.connect(self._open)
self.setSourcePort = setSourcePort
self.config = config
self.saveSourcePortPath = saveSourcePortPath
def _open(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(
self.widget, "Select a source port", self.config.get("sourcePortDir"), "Source Ports (gzdoom zandronum)", options=options)
if fileName:
self.saveSourcePortPath(fileName)
self.setSourcePort(fileName)
在 linux 上,當然,我沒有可執行文件的文件擴展名,但我需要過濾 windows 上的擴展名(我打算提供一個版本)。 此外,沒有允許QDir::Executable的重載方法。 如何在僅過濾可執行文件時使用QFileDialog.getOpenFileName
,無論它在哪個平台上運行?
如果您想要一個更個性化的過濾器,那么您必須使用 proxyModel 但為此您不能使用 getOpenFileName 方法,因為 QFileDialog 實例不容易訪問,因為它是 static 方法。
class ExecutableFilterModel(QSortFilterProxyModel):
def filterAcceptsRow(self, source_row, source_index):
if isinstance(self.sourceModel(), QFileSystemModel):
index = self.sourceModel().index(source_row, 0, source_index)
fi = self.sourceModel().fileInfo(index)
return fi.isDir() or fi.isExecutable()
return super().filterAcceptsRow(source_row, source_index)
class OpenSourcePortAction(QAction):
def __init__(self, widget, setSourcePort, config, saveSourcePortPath):
super().__init__("&Open Source Port", widget)
self.widget = widget
self.setShortcut("Ctrl+O")
self.setStatusTip("Select a source port")
self.triggered.connect(self._open)
self.setSourcePort = setSourcePort
self.config = config
self.saveSourcePortPath = saveSourcePortPath
def _open(self):
proxy_model = ExecutableFilterModel()
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
dialog = QFileDialog(
self.widget, "Select a source port", self.config.get("sourcePortDir")
)
dialog.setOptions(options)
dialog.setProxyModel(proxy_model)
if dialog.exec_() == QDialog.Accepted:
filename = dialog.selectedUrls()[0].toLocalFile()
self.saveSourcePortPath(fileName)
self.setSourcePort(fileName)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.