Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
dmh126 Avatar asked Nov 29 '25 12:11

dmh126


2 Answers

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).

like image 149
ekhumoro Avatar answered Dec 02 '25 01:12

ekhumoro


Try with *.json instead of .json

file = dialog.getSaveFileName(None, "Title", "", "JSON (*.json)");
like image 31
Barmak Shemirani Avatar answered Dec 02 '25 02:12

Barmak Shemirani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!