Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Fun with Paths and URLs in QML

Managing Your QML Assets with Ease

class AssetUrlHandler : public QQmlAbstractUrlInterceptor
{
public:
    AssetUrlHandler() {
        QDir::setSearchPaths("asset",{":/assets", QGuiApplication::applicationDirPath() + "/assets"});
    }
    //...
}
QUrl AssetUrlHandler::intercept(const QUrl& path, QQmlAbstractUrlInterceptor::DataType type)
{
    if (type == QQmlAbstractUrlInterceptor::DataType::QmldirFile)
        return path; // no need to lookup these files; this is about assets, not about QML files

    auto scheme = path.scheme();
    if (scheme == QLatin1String(assetScheme)) {
        QFileInfo fi("asset:" + path.mid(1));
        if (fi.exists()) {
            if (fi.filePath().startsWith(":/")) {
                // we need to deal with files in the resources by adding the url scheme for them
                return QUrl("qrc" + fi.filePath());
            }
            return QUrl::fromLocalFile(fi.filePath());
        }
        return {};
    }
    //followed by other (related) schemes if needed
}
SoundEffect {
    id: someEffect
    source: "file:///" + baseDir + "/assets/someEffect.wav"
}

//...

Image {
    source: "qrc://assets/images/niceImage.png"
}
SoundEffect {
    id: someEffect
    source: "asset:/sounds/someEffect.wav"
}

//...

Image {
    source: "asset:/images/niceImage.png"
}
// property initialization
Image {
    id: img1
    source: "asset:/icons/icon.png"
}

// property binding
Image {
    id: img2
    source: someProperty ? "asset:/icons/icon1.png"
                         : "asset:/icons/icon2.png"
}

// assign through state changes
Image {
    id: img3
}

PropertyChanges { target: img3; source: "asset:/icons/icon.png" }

// assign in JavaScript
Image {
    id: img4

    Component.onCompleted: source = "asset:/icons/icon.png"
}
img1.source === "qrc:///assets/icons/icon.png"
img2.source === "asset:/icons/icon1.png" (or icon2.png)
img3.source === "asset:/icons/icon.png"
img4.source === "asset:/icons/icon.png"

About KDAB


4 Comments

24 - Jun - 2022

Ulf

24 - Jun - 2022

André Somers

27 - Jun - 2022

Ulf

28 - Jun - 2022

André Somers

AndréSomers

André Somers

Senior Software Engineer

Learn Modern C++

Learn more