14

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?

Berschi
  • 2,365
  • 8
  • 33
  • 49
  • 1
    Qt documentation is clear and comprehensive, I'm wondering how could you possibly have missed QFileDialog::setDefaultSuffix() – Julien-L Dec 23 '09 at 16:25
  • 1
    Looks like a lot of works just to do the same as : QFileDialog::getSaveFileName(). Do I miss something ? – Andy M Dec 23 '09 at 16:31
  • 4
    @Julien L.: I usually try to answer the question, not question the need, especially for simple queries like this. However, if the OP would have opened the page I linked to and searched for "extension", he would have found only the example for "setNameFilter", and nothing else related to default suffixes. – Caleb Huitt - cjhuitt Dec 24 '09 at 00:00
  • 1
    @cjhuitt: Exactly, that's the reason I asked this (easy to answer) question – Berschi Dec 24 '09 at 01:15

1 Answers1

19

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 (e.g. "txt" indicates a text file).

Community
  • 1
  • 1
Caleb Huitt - cjhuitt
  • 14,132
  • 2
  • 40
  • 49
  • 7
    How can this be done when there are multiple filetypes allowed? e.g, "All-Files (*.pdf *.txt);;PDF-Files(*.pdf)" and the user selectd the second entry, PDF-Files? – manatttta May 30 '16 at 10:16
  • 2
    @manatttta While not exactly trivial, it should be possible to subclass `QFileDialog`, connect the `filterSelected()` signal to a slot which searches the filter string for the first file extension, and then calls `setDefaultSuffix()` with it. – Parker Coates Feb 06 '17 at 13:42