0

我在 Qt 论坛上阅读了QFile::exists可用于测试图像资源是否存在的信息。

在我的项目中,我有很多图像,QML 文件中的参考之一是:

qrc:/images/ImageViewer/viewer_camera_rear2_off.png

我检查了 Qt Creator 并且资源存在且正确,我在 C++ 中添加了一个名为 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 : "";
}

我已经在 Qt Creator 中对此进行了调试并QFile::exists返回 false,我知道图像和参考是正确且存在的绝对事实,那么 Qt 开发人员论坛上的信息是否错误?

我还尝试将 QRC 前缀更改为:

    qrc:/
    qrc://

结果还是一样 QFile::exists 返回 false。

4

2 回答 2

2

不要使用qrc前缀。
从文档:

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.

于 2020-03-24T11:24:24.793 回答
0

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 :)

于 2020-03-24T11:25:01.140 回答