7

Is there an equivalent of the lpstrDefExt member of OPENFILENAME struct used in the Win32 function GetSaveFileName?

Here's description from MSDN:

LPCTSTR lpstrDefExt

The default extension. GetOpenFileName and GetSaveFileName append this extension to the file name if the user fails to type an extension. This string can be any length, but only the first three characters are appended. The string should not contain a period (.). If this member is NULL and the user fails to type an extension, no extension is appended.

So if lpstrDefExt is set to "txt" and the user types "myfile" instead of "myfile.txt", the function still returns "myfile.txt".

sashoalm
  • 63,456
  • 96
  • 348
  • 677

3 Answers3

6

Edit: If this does not work for you look at the answer below by @user52366

Qt will extract the default extension from the "selectedFilter" parameter, if specified.

Here is an example:

QString filter = "Worksheet Files (*.abd)";
QString filePath = QFileDialog::getSaveFileName(GetQtMainFrame(), tr("Save Worksheet"), defaultDir, filter, &filter);

When using this code the getSaveFileName() method will automatically add the ".abd" file extension if the user didn't specify one in the dialog. You can see the implementation of this in the qt_win_get_save_file_name() inside the "qfiledialog_win.cpp" Qt source file.

Unfortunately this doesn't work for the getOpenFileName() method.

sashoalm
  • 63,456
  • 96
  • 348
  • 677
Fabian
  • 1,670
  • 2
  • 18
  • 33
  • 5
    This doesn't work for me and I cannot a reference to such usage in the documentation. Could you send me a pointer? – Samuel Li Apr 21 '17 at 20:02
1

As mentioned in the comment above, this does not work, at least for me.

In the end I skipped the static method and used the following:

QFileDialog dialog(this, "Save someting", QString(),
                   "Comma-separated file (*.csv)");
dialog.setDefaultSuffix(".csv");
dialog.setAcceptMode(QFileDialog::AcceptSave);
if (dialog.exec()) {
    const auto fn = dialog.selectedFiles().front();
    // a QStringList is returned but it always contains a single file
    // do something using filename 'fn' ...
}
user52366
  • 921
  • 7
  • 17
0

Not sure what exactly LPCTSTR lpstrDefExt is trying to do but Qt documentation gives the following example

 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                            "/home/jana/untitled.png",
                            tr("Images (*.png *.xpm *.jpg)"));

http://doc.qt.io/qt-5/qfiledialog.html#getSaveFileName

Christophe Weis
  • 2,190
  • 4
  • 25
  • 27
blueskin
  • 8,713
  • 10
  • 67
  • 100
  • 1
    In Windows, if you get a Save File dialog from, say, Notepad, and you type just 'a' instead of 'a.txt', the file created wouldn't be 'a.' (i.e. without extension), it would be 'a.txt'. – sashoalm Oct 29 '11 at 15:33