问题
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.
Thanks in advance for your help.
回答1:
Restating what was in the comments for future visitors, the following line puts "myFileName" as the default name in the QFileDialog:
export_dialog->selectFile("myFileName");
Discussion: http://www.qtcentre.org/threads/49434-QFileDialog-set-default-name?highlight=QFileDialog
Not-so-helpful docs: http://qt-project.org/doc/qt-4.8/qfiledialog.html#selectFile
回答2:
I searched google for set default filename qfiledialog
and happened across this discussion.
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"
Hope that helps
回答3:
QString dir = QDir::homePath();
QString name = "test.txt";
QFileDialog::getSaveFileName(nullptr, tr("save file"), dir + "/" + name, tr("TXT (*.txt)"));
If you set "dir" argument, and dir is "file"(exist or not), in windows you will have default name.
回答4:
With the current QT-version (5.x) you can set your preferred file-name with the argument directory
in the QFileDialog.getSaveFileName() function call:
QFileDialog.getSaveFileName( directory = 'preferredFileName.txt' )
docs: http://doc.qt.io/qt-5/qfiledialog.html#getSaveFileName
来源:https://stackoverflow.com/questions/15416334/qfiledialog-how-to-set-default-filename-in-save-as-dialog