5
votes

My application has the following structure:

There is a main.cpp which loads a file named main.qml from a qrc file.

Contents of the qrc:

  • /qml/main.qml
  • /qml/CustomUiElement.qml
  • /qml/WidgetQmlInQrc.qml

In this main.qml, i'm loading other qml components/files, which are also stored in the qrc. This works as expected.

main.qml

Component.onCompleted:{
    var component=Qt.createComponent("WidgetQmlInQrc.qml")
    widget=component.createObject(mainWindow,params)
}

I'd like to use qml components/files stored on the local filesystem in my main.qml.

Local qml file: /mnt/plugin/WidgetQmlExternal.qml

import QtQuick 2.0;

Rectangle {
    color:"green";
    CustomUiElement {
    }    
}

First i tried to extend the qml import path:

viewer->engine()->addImportPath("/mnt/plugin/"); 

This did not work.

After that i tried to load the component by using the full path. Now the WidgetQmlExternal.qml is found and loaded, but it can't find the CustomUiElement.qml because the external qml can't access files in the qrc.

Component.onCompleted:{
    var component=Qt.createComponent("/mnt/plugin/WidgetQmlExternal.qml")
    widget=component.createObject(mainWindow,params)
}

How can i solve this issue / what do i have to change of the structure of my application to be able to load external components, which again reuse some of my custom components?

2

2 Answers

1
votes

Here are some options that come to mind:

Load the internal, QRC-based QML file with a Loader

WidgetQmlExternal.qml:

import QtQuick 2.0

Rectangle {
    anchors.fill: parent
    color: "red"

    Loader {
        source: "qrc:/WidgetQmlInQrc.qml"
    }
}

Interestingly, Qt itself exposes certain assets this way.

Expose the internal, QRC-based QML files as a QML module

You can read more about this here.

4
votes

I also struggled with this until I realised that you can simply prefix the url to force it to look at the local file system, e.g.

Loader {
    source: "file:/mnt/plugin/WidgetQmlExternal.qml"
}

Using this approach, the component loaded by the Loader will be able to access other components withing the QRC as well. Hope that helps.