QT 5.4, Unable to access Resource from code

a 夏天 提交于 2019-12-02 19:16:41

问题


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.



来源:https://stackoverflow.com/questions/29073163/qt-5-4-unable-to-access-resource-from-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!