QFile testing for existence of qrc resource

1.4k views Asked by At

I read on the Qt forums that QFile::exists can be used to test for existence of an image resource.

In my project I have a lot of images, one of the references in a QML file is to:

qrc:/images/ImageViewer/viewer_camera_rear2_off.png

I've checked in Qt Creator and the resource is present and correct, I have added a function to the C++ called checkImage:

QString Manager::checkPath(QString path) {
    bool valid = false;

    if ( path.length() > 0 && path.indexOf(".") > 0 ) {
        const QString QRCprefix("qrc:");

        if ( path.startsWith(QRCprefix) != true ) {
            const QString imgsPath("/images/");

            if ( path.startsWith(imgsPath) != true ) {
              path = imgsPath + path; /*Thank you @WilliamMiller*/
            }
            path = QRCprefix + path;
        }
        valid = QFile::exists(path);
    }
    return (valid == true) ? path : "";
}

I've debugged this in Qt Creator and QFile::exists returns false, I know for an absolute fact that the image and reference is correct and exists, so is the information on the Qt developers forum wrong?

I've also tried changing the QRC prefix to:

    qrc:/
    qrc://

Result is still the same QFile::exists returns false.

2

There are 2 answers

0
Vladimir Bershov On BEST ANSWER

Do not use qrc prefix.
From the docs:

Using Resources in the Application
In the application, resource paths can be used in most places instead of ordinary file system paths. In particular, you can pass a resource path instead of a file name to the QIcon, QImage, or QPixmap constructor:

cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);

See the Application example for an actual application that uses Qt's resource system to store its icons.

0
SPlatten On

I read on the Qt Developer forum that an alternative to "qrc:/" is to use just ":/", so the new URI is:

    :/images/ImageViewer/viewer_camera_rear2_off.png

Now QFile::exists returns true and all is right in the world :)