Specify default extension in QFileDialog::getSaveFileName

sashoalm picture sashoalm · Aug 29, 2011 · Viewed 7.9k times · Source

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

Answer

Fabian picture Fabian · Apr 9, 2013

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.