Qt World Summit: Register Today!


Assign default path to QFileDialog



  • Hello everyone,
    I'm making a notepad and I'm currently working on the open and save button.
    How do I set the default path of those to the Desktop?

    fileName = QFileDialog::getSaveFileName(this, tr("Save a file"), "C:/Users/<USER>/Desktop/", tr("Text File (*.txt);; RichTextFormat File (*.rtf);; All Files (*)"));
        }
    

    This doesn't work. How do I solve this?



  • @HenkCoder

    Hello!

    Check out my example:

     QString desktopPath = QDir::toNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
     qDebug() << "Desktop path: " << desktopPath;
     QString fileName = QFileDialog::getSaveFileName(this, QObject::tr("Save a file"), desktopPath, QObject::tr("Text File (*.txt);; RichTextFormat File (*.rtf);; All Files (*)"));
     qDebug() << fileName;
    
      if (!fileName.isEmpty()) {
          QFile *saveFile = new QFile(fileName);
          saveFile->open(QIODevice::WriteOnly);
          QTextStream saveStream(saveFile);
          saveStream << "This is a text example...";
          saveFile->close();
          saveFile->deleteLater();
      }
    

    My code will save the file to the Desktop location. Keep in mind, to save the actual file, you must use QFile with QTextStream. Happy coding!


  • Lifetime Qt Champion



  • @Christian-Ehrlicher
    I already tried it but it doesn't work


  • Lifetime Qt Champion

    @HenkCoder said in Assign default path to QFileDialog:

    but it doesn't work

    This is no error description... it works perfectly fine for me. Please show us your code.



  • @Christian-Ehrlicher
    Can you just tell me how to make it?
    I wrote that code like yesterday and I don't remember what I did.
    Thank you for answering



  • @HenkCoder

    Hello!

    Check out my example:

     QString desktopPath = QDir::toNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
     qDebug() << "Desktop path: " << desktopPath;
     QString fileName = QFileDialog::getSaveFileName(this, QObject::tr("Save a file"), desktopPath, QObject::tr("Text File (*.txt);; RichTextFormat File (*.rtf);; All Files (*)"));
     qDebug() << fileName;
    
      if (!fileName.isEmpty()) {
          QFile *saveFile = new QFile(fileName);
          saveFile->open(QIODevice::WriteOnly);
          QTextStream saveStream(saveFile);
          saveStream << "This is a text example...";
          saveFile->close();
          saveFile->deleteLater();
      }
    

    My code will save the file to the Desktop location. Keep in mind, to save the actual file, you must use QFile with QTextStream. Happy coding!



  • @Cobra91151 Hey! Sorry for the late answer, I was busy lately. Alright, I'm going to try it, thank you for answering and happy coding to you too!


Log in to reply