Can't load qrc files in a Qt C++ program

1.4k Views Asked by At

I am trying load a CSS file to the program using qrc. But at run time I get the following error:

QIODevice::read (QFile, ":/css/stylesheet.qss"): device not open

I am using CMake, here is my project's structure:

.
├── calculator.cpp
├── calculator.h
├── calculator.ui
├── CMakeLists.txt
├── CMakeLists.txt.user
├── css
│   └── stylesheet.qss
├── main.cpp
└── resources.qrc

CMake file:

cmake_minimum_required(VERSION 3.9)

project(Calculator)

set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}  -Wall -Wpedantic -Wextra -std=gnu++14")

find_package(Qt5Widgets REQUIRED)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTORCC ON)


add_executable(${PROJECT_NAME} main.cpp calculator.cpp )
target_link_libraries(Calculator Qt5::Widgets)

And here is the main.cpp file which uses the qrc file:

#include <QApplication>
#include <QFile>
#include "calculator.h"
#include <QtDebug>

int main(int argc,char **argv)
{
    QApplication *app= new QApplication(argc,argv);
//  Q_INIT_RESOURCE(resources);

    QFile css(":/css/stylesheet.qss");
    if(css.open(QIODevice::ReadOnly ))
    {
        app->setStyleSheet(css.readAll());
        css.close();
    }else
    {
        qDebug("Failed") ;
        qDebug(css.readAll());
    }

    Calculator *cal = new Calculator(nullptr);
    cal->show();

    return  app->exec();

}

resources.qrc file:

<RCC>
    <qresource prefix="/">
        <file>css/stylesheet.qss</file>
    </qresource>
</RCC>

Whenever I try to run, I get this output:

qt5ct: using qt5ct plugin
Failed
QIODevice::read (QFile, ":/css/stylesheet.qss"): device not open

I am using Arch Linux and gcc (GCC) 7.3.1 with Qt Creator and I am new to CMake and Qt.

2

There are 2 best solutions below

0
On BEST ANSWER

Add the resource to the add_executable()

add_executable(${PROJECT_NAME} main.cpp calculator.cpp resources.qrc) // added qrc
2
On

please add your QRC resource in your makefile.

RESOURCES += resources.qrc