Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Open-file dialog returning gibberish?



  • I've tried using the open-file dialog to get a filename or file path and it consistently gives a gibberish value:

    QString filename = QFileDialog::getOpenFileName(this,
                    "Open text file", getenv("HOME"), "Text Files (*.txt)");
            const char *path = filename.toStdString().c_str();
    

    The result is always a string that is nothing like the filename that was selected.
    What is the correct way to get a C string path or filename from QFileDialog?


  • Lifetime Qt Champion

    @Publicnamer said in Open-file dialog returning gibberish?:

    The result is always a string that is nothing like the filename that was selected.

    I would be surprised if you would return something valid... You create a temporary std::string which goes out-of-scope immediatelly.
    Why do you need a const char* for this at all?

    QString filename = ...
    std::string filenameStd = filename.toStdString();
    const char *path = filenameStd .c_str();
    

  • Lifetime Qt Champion

    Hi,

    @Publicnamer said in Open-file dialog returning gibberish?:

    const char *path = filename.toStdString().c_str();

    You are keeping the address of a temporary std::string that you convert to a c string.

    So there's a high chance that path points to garbage memory.


Log in to reply