How to convert Qt file path from resource to absolute path?
Asked Answered
B

1

7

I need to receive the absolute file path like

C:/Users/Dima/YandexDisk/_Application/WeldAnalysis/ExperimentDefaults.xlsx

from path of QRC file like

:/Data/ExperimentDefaults.xlsx.

How can I do this?

Bingaman answered 9/5, 2017 at 22:27 Comment(3)
qrc is itself a file and a collection of resource files embedded to executable files and no longer mapped to OS file system. Even if you can see file paths in that qrc file they supposed to be all compacted in one collective resource file.Danialah
If the resource file dir. is the one of the application itself then this might help: QCoreApplication::applicationDirPath() and, even better, its static. I found this in SO: How to find the installation directory of a Qt application?.Coyote
I think you can't because data is compiled into the binary, according to the Qt resource docMerideth
K
4

Resources are packed all together into the QRC file, they are not exposed to the filesystem, thus they cannot be converted to a standard path; it is like accessing a file inside a zip file.

What are you willing to do with such file path? QFile can deal with resource paths (":/...") and open such files, but other file handling APIs don't (such as C's fopen or C++'s std::ifstream). Also, and for the same reason, non-Qt application won't be able to open such files if passed as a parameter.

Options you have include:

  • opening the file using QFile and read it using related Qt classes (given you are dealing with an Excel file I think it doesn't worth the effort, unless you have some library to read it from a memory buffer).

  • copying the file out of the resources container to a temporary directory (you can use QTemporaryDir to create one), and use the file from there:

    QTemporaryDir tempDir;
    if (tempDir.isValid()) {
      const QString tempFile = tempDir.path() + "/yourfile.xlsx";
      if (QFile::copy(":/yourfile.xlsx", tempFile)) {
        // your file is now extracted to the filesystem
      }
    }
    

Only be aware that when tempDir is destroyed, the temporary directory is also deleted, therefore your file. You can avoid this by disabling the auto-remove feature: tempDir.setAutoRemove(false) and manually deleting the temporary directory when you finish with the extracted file.

Kicker answered 10/5, 2017 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.