In Qt, use resources not located in the source directory

1.6k views Asked by At

I need to use a set of resources from several different programs (images, fonts, txt files, etc). So I put them in a common folder. So I try to read one of these txt files using this path:

":/../../CommonClasses/PNGWriter/report_text/English"

However this does not work as the the QFile cannot be opened for reading with this path.

Hoewever if I move the report_text directory to the source directory and use this path:

":/report_text/English"

Then it all works just fine.

So my question is, is it possible to user resources not located in the source directory?

EDIT:

Here is my .qrc source file (and I replaced stuff.txt with an actual file from my resource file)

<RCC>
    <qresource prefix="/">
        <file>../../CommonClasses/PNGWriter/report_text/English</file>
        <file>../../CommonClasses/PNGWriter/report_text/GothamBlackRegular.otf</file>
        <file>../../CommonClasses/PNGWriter/report_text/GothamBold.otf</file>
        <file>../../CommonClasses/PNGWriter/report_text/GothamBook.otf</file>
        <file>../../CommonClasses/PNGWriter/report_text/GothamLight.otf</file>
        <file>../../CommonClasses/PNGWriter/report_text/GothamMedium.otf</file>
        <file>../../CommonClasses/PNGWriter/report_text/Spanish</file>
        <file>../../CommonClasses/PNGWriter/report_text/viewmind.png</file>
    </qresource>
</RCC>
3

There are 3 answers

5
timday On

The alias keyword is useful for giving things a different name in the resource system.

Instead of

<file>../../CommonClasses/PNGWriter/report_text/viewmind.png</file>

you'd write

<file alias="report_text/viewmind.png">../../CommonClasses/PNGWriter/report_text/viewmind.png</file>

Of course, this is bit of a pain if you're manually maintaining large qrc files; it may be useful to automate (script) production of them.

2
AudioBubble On

I don't believe this is a native option, as when I try to add files above the project sub-directory I get "The file "/path/to/file/" is not in a subdirectory of the resource file. You now have the option to copy this file to a valid location.", with the copy option.

However, (if on linux) adding a symbolic link to the resource file in the project subdirectory works perfectly fine for me. So something like ln -s /path/to/target/resource /path/to/project/directory/resource_name.file, and then adding resource_name.file to your resources file should work. It does on mine (Qt 5.7).

0
aarelovich On

Thank to the friendly tip @timday, I've managed to see what the problem is. The ../../ that I used were the problem. The path to the file was actually:

:/CommonClasses/PNGWriter/report_text/English

Now it works just as expected!! I hope this helps anyone else with this problem!