Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify default extension in QFileDialog::getSaveFileName

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

like image 880
sashoalm Avatar asked Aug 29 '11 18:08

sashoalm


2 Answers

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.

like image 150
Fabian Avatar answered Sep 22 '22 13:09

Fabian


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' ...
}
like image 33
user52366 Avatar answered Sep 22 '22 13:09

user52366