QFileDialog: how to set default filename in "Save as..." dialog

Denis Shevchenko picture Denis Shevchenko · Mar 14, 2013 · Viewed 18.2k times · Source

I try to create "Save as..." dialog in Mac OS X. But I don't want to use QFileDialog::getSaveFileName() function, because dialog that created by this function is NOT truly-native in Mac OS X Lion. So I decide to create dialog as QFileDialog object:

auto export_dialog( new QFileDialog( main_window ) );
export_dialog->setWindowModality( Qt::WindowModal );
export_dialog->setFileMode( QFileDialog::AnyFile );
export_dialog->setAcceptMode( QFileDialog::AcceptSave );

All works fine, except one problem. I cannot set default name for saved file, so user must type this name manually every time. I know that function QFileDialog::getSaveFileName() allows to set default filename via third argument, dir (http://qt-project.org/doc/qt-4.8/qfiledialog.html#getSaveFileName). But how to set this default name without this function?

I can set default suffix for saved file via QFileDialog::setDefaultSuffix() function, but I need to set whole default name, not only default suffix.

I've tried to use QFileDialog::setDirectory() function, but it sets only directory where to save, without name of saved file.

I use Qt 4.8.1 on Mac OS X Lion.

Answer

Louis Parkin picture Louis Parkin · Mar 5, 2015

I have found that using selectFile("myFileName"); only works if the file actually exists. In my case, the intent is to create a new file with the option of overwriting an existing file.

The solution that worked for me (Qt 5.3.2) was as follows:

QFileDialog svDlg;

QString saveFileName = svDlg.getSaveFileName(this, caption, preferredName, filter);

In the above example, preferredName is a QString that contains "C:/pre-selected-name.txt"