Robbert
Robbert

Reputation: 5193

Using a Loader for a string of QML

In Qt 5.3 I've been using the Loader QML element for loading screens, loading the view from a QML file in the background. Now I'm trying to load a string of QML dynamically. Qt.createQmlObject enables me to do so, but I can't seem to get the Loader element to play along.

Seems like Loader only takes a URL (QUrl) or component (QQmlComponent), but Qt.createQmlObject creates an object (QObject).

I'm new to QML, but from my understanding components are reusable elements, similar to classes, and objects are the instances of those classes. I thus can't seem to wrap my head around why Loader wouldn't work with objects.

How can I show a loading screen while (asynchronously) parsing and initializing a string of QML?

Example QML code:

Item {
    Rectangle {id: content}

    Loader {id: loader}

    Component.onCompleted: {
        var obj = Qt.createQmlObject('import QtQuick 2.3; Rectangle {}', content);

        loader.source = obj; // Throws error.
    }
}

Upvotes: 3

Views: 2067

Answers (1)

Mitch
Mitch

Reputation: 24396

It's not possible using the current API. As Loader's documentation says, it loads objects via a URL that points to a QML file or a Component:

import QtQuick 2.0

Item {
    Rectangle {
        id: content
        anchors.fill: parent
        color: "grey"

        Loader {
            id: loader
            sourceComponent: myComponent
            anchors.fill: parent
            anchors.margins: 40
        }
    }

    property Component myComponent: Qt.createComponent("MyComponent.qml", Component.Asynchronous)
}

MyComponent.qml:

import QtQuick 2.2

Rectangle {
   color: "red"
}

Upvotes: 1

Related Questions