When using a QFileDialog
to save a file and to specify the extension (like *.pdf) and the user types in a name without this extension, also the saved file hasn't this extension.
Example-Code:
QFileDialog fileDialog(this, "Choose file to save");
fileDialog.setNameFilter("PDF-Files (*.pdf)");
fileDialog.exec();
QFile pdfFile(fileDialog.selectedFiles().first());
now when the user enters "foo" as the name, the file will be saved as "foo", not as "foo.pdf". So the QFileDialog
doesn't add the extension automatically. My question: How can I change this?
You could use QFileDialog::setDefaultSuffix() :
This property holds suffix added to the filename if no other suffix was specified.
This property specifies a string that will be added to the filename if it has no suffix already. The suffix is typically used to indicate the file type (eg "txt" indicates a text file).
For multiple file filters, the following can be done.
import re
import os
def saveFile(self):
path, fileFilter = QFileDialog().getSaveFileName(self, "Save file",
"", "Gnuplot Files (*.plt)"
+ ";;" + "Gnuplot Files (*.gp)"
+ ";;" + "Gnuplot Files (*.gpt)"
+ ";;" + "Text Files (*.txt)")
selectedExt = re.search('\((.+?)\)',fileFilter).group(1).replace('*','')
# Attach extension as per selected filter,
# if file does not have extension.
if not os.path.splitext(path)[1]:
path = path + selectedExt
print(path)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.