Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to check if a resource exists?



  • I'm trying to defeat the QML messages that come up when an image isn't present or doesn't exist.

    In my C++ function I have written a helper function:

    QString Manager::checkPath(QString path) {
        bool valid = false;
        if ( path.length() > 0 && path.indexOf(".") > 0 ) {
            const String QRCprefix("qrc:");
            if ( path.startsWith(QRCprefix) != true ) {
                const QString imgsPath("/images/");
                if ( path.startsWith(imgsPath) != true ) {
                  path += imgsPath;
                }
                path = QRCprefix + path;
            }
            valid = QFile::exists(path);
        }
        return (valid == true) ? path : "";
    }
    

    I'm calling this from the QML, as an example I can see in Qt Creator a valid reference is passed:

    qrc:/images/ImageViewer/viewer_camera_rear2_off.png
    

    However, when it gets to call QFile::exists(), this returns false. I've read elsewhere on these forums that QFile::exists can be used on resources, however my findings suggest either I'm doing something wrong or this isn't the case.

    Can anyone tell me?


  • Moderators

    Last resort is to check ":/images" but I suspect it to fail as well.

    Can you paste here the relevant line from your .qrc file?


  • Moderators

    @SPlatten said in How to check if a resource exists?:

    qrc:

    QFile does not understand this part. In order for QFile to get it, you need a different URL:

    qrc:///images/ImageViewer/viewer_camera_rear2_off.png
    


  • No difference, still returns false.

    Have tried:

    qrc:/images/ImageViewer/viewer_camera_rear2_off.png
    qrc://images/ImageViewer/viewer_camera_rear2_off.png
    qrc:///images/ImageViewer/viewer_camera_rear2_off.png

    All return false, yet the path is valid.


  • Moderators

    Last resort is to check ":/images" but I suspect it to fail as well.

    Can you paste here the relevant line from your .qrc file?



  • I am trying that now, funny enough I thought the same, refreshed and saw your suggestion.



  • :/images/ImageViewer/viewer_camera_rear2_off.png
    

    Works! And now QFile::exists returns true, thank you!


  • Moderators

    Nice! Happy coding


Log in to reply