开发者

Specify default extension in QFileDialog::getSaveFileName

Is there an equivalent of t开发者_如何学Che 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".


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.


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' ...
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜