Skip to content Skip to sidebar Skip to footer

Pyqt Qfiledialog Custom Proxy Filter Not Working

This working code brings up a QFileDialog prompting the user to select a .csv file: def load(self,fileName=None): if not fileName: fileName=fileDialog.getOpenFi

Solution 1:

Found the solution at another stackoverflow question here.

From that solution:

The main thing to watch out for is to call dialog.setOption(QFileDialog::DontUseNativeDialog) before dialog.setProxyModel.

Also it looks like you then have to use fileDialog.exec_() rather than fileDialog.getOpenFileName. The value you set to setNameFilter does show up in the filter cyclic field of the non-native dialog, but is effectively just for decoration since the proxymodel filter overrides it. In my opinion that is a good thing since you can put wording in the filter cyclic that would indicate something useful to the user as to what type of filtering is going on.

Thanks to users Frank and ariwez.

UPDATE: to clarify, here's the full final code I'm using:

defload(self,fileName=None):
    ifnot fileName:
        fileDialog=QFileDialog()
        fileDialog.setOption(QFileDialog.DontUseNativeDialog)
        fileDialog.setProxyModel(CSVFileSortFilterProxyModel(self))
        fileDialog.setNameFilter("CSV Radio Log Data Files (*.csv)")
        fileDialog.setDirectory(self.firstWorkingDir)
        if fileDialog.exec_():
            fileName=fileDialog.selectedFiles()[0]
        else: # user pressed cancel on the file browser dialogreturn... (the rest of the load function processes the selected file)
...


# code for CSVFileSortFilterProxyModel partially taken from#  https://github.com/ZhuangLab/storm-control/blob/master/steve/qtRegexFileDialog.pyclassCSVFileSortFilterProxyModel(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 casedeffilterAcceptsRow(self,source_row,source_parent):
#       print("CSV filterAcceptsRow called")
        source_model=self.sourceModel()
        index0=source_model.index(source_row,0,source_parent)
        # Always show directoriesif source_model.isDir(index0):
            returnTrue# filter files
        filename=source_model.fileName(index0).lower()
#       print("testing lowercased filename:"+filename)# never show non- .csv filesif filename.count(".csv")<1:
            returnFalseif filename.count("_fleetsync.csv")+filename.count("_cluelog.csv")==0:
            returnTrueelse:
            returnFalse

Post a Comment for "Pyqt Qfiledialog Custom Proxy Filter Not Working"