Search code examples
pythonpyqtpyqt4qfiledialog

Can't add extension to file in QFileDialog


I've got a problem with saving file with extension (get path to file and append extension) in PyQt4 with QFileDialog. My Python code looks like that:

dialog = QtGui.QFileDialog()
dialog.setDefaultSuffix(".json")
file = dialog.getSaveFileName(None, "Title", "", "JSON (.json)")

It works, path is correct, dialog title and filter are in dialog window, but second line was ignored. File doesn't have any extension.

How to add extension by default? What am I doing wrong?


Solution

  • Calling setDefaultSuffix on an instance of QFileDialog has no effect when you use the static functions. Those functions will create their own internal file-dialog, and so the only options that can be set on it are whatever is made available via the arguments.

    Of course, setDefaultSuffix will work if the instance of QFileDialog is shown directly:

    dialog = QtGui.QFileDialog()
    dialog.setFilter(dialog.filter() | QtCore.QDir.Hidden)
    dialog.setDefaultSuffix('json')
    dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
    dialog.setNameFilters(['JSON (*.json)'])
    if dialog.exec_() == QtGui.QDialog.Accepted:
        print(dialog.selectedFiles())
    else:
        print('Cancelled')
    

    But note that you cannot get a native file-dialog using this method.

    If the file-name filters are specified correctly (see above, and Barmak Shemirani's answer), the native file-dialog may provide a means of automatically selecting the filename extension (this is certainly the case with KDE on Linux, but I don't know about other platforms).