【发布时间】:2021-02-15 05:41:14
【问题描述】:
这个工作代码会弹出一个 QFileDialog 提示用户选择一个 .csv 文件:
def load(self,fileName=None):
if not fileName:
fileName=fileDialog.getOpenFileName(caption="Load Existing Radio Log",filter="csv (*.csv)")[0]
...
...
现在,我想将该过滤器更改为更具选择性。该程序将每个项目保存为一组三个 .csv 文件(project.csv、project_fleetsync.csv、project_clueLog.csv),但我只希望文件对话框显示第一个(project.csv)以避免向用户展示选择太多,而 load() 函数的其余部分只能处理其中的三分之一。
根据this 的帖子,看起来解决方案是使用代理模型。因此,我将代码更改为以下内容(load() 中的所有注释行都是我尝试过的各种组合):
def load(self,fileName=None):
if not fileName:
fileDialog=QFileDialog()
fileDialog.setProxyModel(CSVFileSortFilterProxyModel(self))
# fileDialog.setNameFilter("CSV (*.csv)")
# fileDialog.setOption(QFileDialog.DontUseNativeDialog)
# fileName=fileDialog.getOpenFileName(caption="Load Existing Radio Log",filter="csv (*.csv)")[0]
# fileName=fileDialog.getOpenFileName(caption="Load Existing Radio Log")[0]
# fileDialog.exec_()
...
...
# code for CSVFileSortFilterProxyModel partially taken from
# https://github.com/ZhuangLab/storm-control/blob/master/steve/qtRegexFileDialog.py
class CSVFileSortFilterProxyModel(QSortFilterProxyModel):
def __init__(self,parent=None):
print("initializing CSVFileSortFilterProxyModel")
super(CSVFileSortFilterProxyModel,self).__init__(parent)
# filterAcceptsRow - return True if row should be included in the model, False otherwise
#
# do not list files named *_fleetsync.csv or *_clueLog.csv
# do a case-insensitive comparison just in case
def filterAcceptsRow(self,source_row,source_parent):
print("CSV filterAcceptsRow called")
source_model=self.sourceModel()
index0=source_model.index(source_row,0,source_parent)
# Always show directories
if source_model.isDir(index0):
return True
# filter files
filename=source_model.fileName(index0)
# filename=self.sourceModel().index(row,0,parent).data().lower()
print("testing lowercased filename:"+filename)
if filename.count("_fleetsync.csv")+filename.count("_clueLog.csv")==0:
return True
else:
return False
当我调用 load() 函数时,我确实得到了“正在初始化 CSVFileSortFilterProxyModel”输出,但显然 filterAcceptsRow 没有被调用:没有“CSV filterAcceptsRow 调用”输出,以及 _fleetsync.csv 和 _clueLog.csv文件仍然在对话框中列出。显然我做错了什么......?
【问题讨论】: