Can't add extension to file in QFileDialog

给你一囗甜甜゛ 提交于 2020-07-21 11:23:05

问题


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?


回答1:


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




回答2:


Try with *.json instead of .json

file = dialog.getSaveFileName(None, "Title", "", "JSON (*.json)");


来源:https://stackoverflow.com/questions/29835413/cant-add-extension-to-file-in-qfiledialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!