سؤال

Using QFileDialog, I want to prompt the user for a filename and add the extension if it is missing.

One suggestion was to just manually add the extension after the fact. The problem with this approach is that the user may not be warned that they are overwriting a file (for example, test.txt exists, the user enters test and is not prompted that they are actually overwriting test.txt)

I have read all the documentation on QFileDialog and have not had any success. I've tried setDefaultSuffix, but the result of fileDialog.getSaveFileName() did not contain the extension. Can someone provide an example of how to do this successfully?

هل كانت مفيدة؟

المحلول

Unfortunately, it looks like this functionality is not available when you're using the "native" file dialog. However, it works just as you expected if you use the Qt file dialog.

Here's how you can use the Qt file dialog:

QFileDialog saveDialog;
saveDialog.setAcceptMode(QFileDialog::AcceptSave);
saveDialog.setDefaultSuffix("txt");
saveDialog.exec();
QString file = saveDialog.selectedFiles().first();

As an alternative, you can implement your own overwrite validation:

QString file;
do 
{
  file = QFileDialog::getSaveFileName();
  if(!file.endsWith(".txt"))
  {
    file.append(".txt");

    if(QFile::exists(file))
    {
      if(QMessageBox::Yes != QMessageBox::question(NULL, QString(), "Confirm overwrite?", QMessageBox::Yes | QMessageBox::No))
      {
        file.clear();
      }
    }
  }
} while (file.isEmpty());
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top