Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching between qrc and local path for qml files

Tags:

qt

qml

As far as i know, the qml files could be loaded from local directory path or could be bundled in qrc file and loaded with qrc:/ URI. In debugging phase changing local qml files doesn't need recompilation of qrc file and linking together with main executable, which is fast procedure for try and error fine tuning. But in deploy phase, the qml files should be bundled together as qrc file and link to main C++ Qt application. This is good practice when you want have single executable file, however compiling qrc file and linking it again is time consuming for big projects. is there any way we can switch to qrc or local directory? for example in debug and release mode?

There is many qml components inside the project and all of these are created by URI's like qrc:/componenentname.qml inside another qml files.

So is there any way to interchange these two states in debug and release modes, and keeping qml files without duplicate changes?

like image 233
e.jahandar Avatar asked Dec 25 '16 07:12

e.jahandar


2 Answers

All URLs inside QML, if not specified in full, are relative to the current file.

E.g. if a QML file has content like this

Image {
    source: "images/foo.png"
}

then the full URL of the image is constructed at runtime based on the base URL of the QML file itself.

I.e. if the QML file itself is qrc://main.qml then the resulting path is qrc://images/foo.png, if the QML file itself is file:///path/to/your/project/main.qml then the resulting image source is file:///path/to/your/project/image/foo.png.

So if you keep URLs relative in your usage inside QML, you can simply switch between resource and local files when loading the primary QML file.

QUrl mainFile = localMode ? QUrl::fromLocalFile("main.qml") : QUrl("qrc://main.qml")

QQuickView view;
view.setSource(mainFile);
like image 139
Kevin Krammer Avatar answered Oct 24 '22 08:10

Kevin Krammer


Sorry for the old post,

What we did to handle this is use Qts resource search path. We used PySide2 so examples are in python

try:
    QDir.addSearchPath('search_path_name', 'path/to/root/resources')
    engine.load('search_path_name:/main.qml')

except FileNotFoundError:
    try:
        import qml # compiled resources using pyside resource compiler
        QDir.addSearchPath('search_path_name', ':/')
        engine.load('qrc:///main.qml')
    except ModuleNotFoundError:
            pass

From this point on resources are loaded using QFile("search_path_name:some_file.txt") and it will load from either search path.

like image 1
Apeiron Avatar answered Oct 24 '22 08:10

Apeiron