QT 5.4, Unable to access Resource from code

2019-03-03 20:59发布

问题:

I try to include style images of my app into a q-resource file. When I include the file directly in the code, it work, but when i try to use QResource, it fail (do not load the file).

I have the resource file in the main directory:

AppFolder
  |- main.cpp
  |- darkstyle.qrc
  |- darkstyle
       |- WindowTitleBar.png

The following example print: failed1 failed2

#include <QApplication>
#include <QResource>
#include <Qfile>
#include <QDebug>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    bool ok= QResource::registerResource("darkstyle.qrc");
    if (!ok) qDebug()<<"failed1";

    QFile file(":/darkstyle/WindowTitleBar.png");
    //QFile file("../AppFolder/darkstyle/WindowTitleBar.png"); //that work

    if(!file.open(QFile::ReadOnly | QFile::Text)) qDebug()<<"failed2";
    else file.close();

    //return a.exec();
    return 0;
}

Note: Qt creator by default create binaries (.exe) in a top folder: ../build-AppFolder_Qt_5_4_1_MSVC2013_64bit-Debug/debug/AppFolder.exe The execution root path seem to be: ../build-AppFolder_Qt_5_4_1_MSVC2013_64bit-Debug

I tried most of possible combinations with execution paths.

Note2: Some examples use a .rcc file format, I have none of these, but that could be a clue.

Summary: How to access a QResource file from inside a QT app?

EDIT 1: Content of qrc file:

<RCC>
    <qresource prefix="/">
        <file>darkstyle/WindowTitleBar.png</file>
        <file>darkstyle/WindowTitleButton.png</file>
        <file>darkstyle/WindowTitleButton1.png</file>
        <file>darkstyle/WindowTitleButton2.png</file>
        <file>darkstyle/WindowTitleButton3.png</file>
    </qresource>
</RCC>

回答1:

QResource::registerResource("darkstyle.qrc") registers the resource description. If you want to use resources dynamically like this you need to register the compiled resources themselves. Run rcc -binary darkstyle.qrc -o darkstyle.rcc and use QResource::registerResource("darkstyle.rcc")

Alternatively, compile the resources into your binary directly. Do do so, use RESOURCES += darkstyle.qrc in your .qrc, and leave out the QResource::registerResource.



回答2:

The problem is related to an incompatibility of the given version of QT with MSVS2013. The problem is solved by downloading another version of QT or visual studio.



标签: c++ qt qresource