tags:

views:

823

answers:

1

Is it possible to map a resource in QT 4.5?

For example:

QFile file(resource_name);

file.open(QIODevice::ReadOnly);

uchar* ptr = file.map(0, file.size());

When I try this, ptr == 0, indicating an error.

It works fine if I try to map a regular file.

I am running qt on linux, which supports QFile::Map.

+1  A: 

Yes, it is possible. There is one thing to keep in mind though. By default the qt resource compiler rcc compresses the resources.

The file.size() call will return the actual, un-compressed size of the original file. However, the embedded resource is compressed and is most likely a different size. The file.map(0, file.size()) returns an error since the size passed to map() is larger than the resource being mapped. Even if you pass the correct size to map(), or a smaller size, the memory will contain the compressed data, not the un-compressed data.

The solution is to not compress the embedded resource. This can be accomplished by adding:

QMAKE_RESOURCE_FLAGS += -no-compress

to your qt project file. See here for explanation of QMAKE_RESOURCE_FLAGS.

Karl Voigtland
Question and answer within one minute ...
Matthieu
I thought this was encouraged as long as it is something that others might find useful. It seems there is a badge for it as well. See here: http://stackoverflow.com/questions/209329/stackoverflow-should-i-answer-my-own-question-or-not , here: http://stackoverflow.com/questions/2572/is-it-poor-etiquette-to-answer-your-own-question and here: http://stackoverflow.com/questions/252194/how-to-earn-the-self-learner-badge.
Karl Voigtland