'selectedFilters' is not a valid keyword a

2019-04-15 17:10发布

问题:

I use PyQt5 and I have an error when I try to save the file name :

 csv_file_list = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '', '*.csv')
    fileName = csv_file_list 
    fileName = QtWidgets.QFileDialog.getSaveFileName(self, 'Dialog Title', '/path/to/default/directory', selectedFilters='*.txt')
    if fileName:
        print (fileName)

And it display me this error : 'selectedFilters' is not a valid keyword argument.

I don't know if the error is here because of PyQt5 or not

回答1:

For various reasons, the C++ signatures don't always exactly match the PyQt signatures. This is probably the biggest weakness of PyQt5. There really needs to be a comprehensive reference that details all the differences between the C++ APIs and the PyQt APIs. It sort of exists for PyQt4, in the form of the PyQt Class Reference (which is a partially converted version of the Qt documentation). But there is currently nothing equivalent to that for PyQt5. However, you can always use python's introspection methods to work out the differences for yourself.

Here's the C++ signature for getSaveFileName:

QString getSaveFileName(QWidget *parent = Q_NULLPTR,
                        const QString &caption = QString(),
                        const QString &dir = QString(),
                        const QString &filter = QString(),
                        QString *selectedFilter = Q_NULLPTR,
                        Options options = Options()
                        )

And here's the PyQt5 signature, which was obtained from the help function in a python interactive session - i.e. help(QtWidgets.QFileDialog.getSaveFileName):

getSaveFileName(parent: QWidget = None,
                caption: str = '',
                directory: str = '',
                filter: str = '',
                initialFilter: str = '',
                options: Union[QFileDialog.Options, QFileDialog.Option] = 0,
                ) -> Tuple[str, str]

As you can see, the dir argument has changed to directory, and the selectedFilter argument has changed to initialFilter.