Search code examples
pythonpyqt5pyside2qfiledialogqmediaplayer

How to solve an issue with QFileDialog's filter parameter?


I want to create a file dialog, using QFileDialog, to choose an audio file to set in QMediaPlayer with a file extension mask (*.mp3, *.ogg, *.flac). Unfortunately, it doesn't work as it should be taking the last extension as a filter property.

I've tried this for PyQt5 and PySide2, result is same. It shows files with the latest extension in the filter list e.g *.mp3 or *.flac only

audioFormats = "*.mp3, *.wav, *.ogg, *.wma, *.flac"
print(f"these are formats: {audioFormats}")
self.track, _ = self.getOpenFileName(parent=self, caption="Set track file", filter=f"Audio files ({audioFormats})")

I'm expected it to show files with all these extensions.


Solution

  • As the example of the docs indicates, you should not use commas to separate the extensions:

    from PyQt5 import QtWidgets
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        audioFormats = "*.mp3 *.wav *.ogg *.wma *.flac" # without commas
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(parent=None, 
            caption="Set track file",
            filter=audioFormats)
        if filename:
            print(filename)