3

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.
    }
}

1 Answer 1

1

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"
}
Sign up to request clarification or add additional context in comments.

5 Comments

Hi Mitch, thanks for chiming in. Though this is a good example of a Loader loading a QML file, I'm actually looking for a way to apply a Loader to a QML string. In other words: is there some way to do Qt.createComponent(QString string) rather than Qt.createComponent(QUrl url)?
No, that's what my answer was trying to say. I've updated it.
Still, there should be some way to load strings of QML asynchronously. Perhaps I need to write a Loader subclass. Either way, thanks for your input Mitch.
No worries. You may want to create a suggestion on bugreports.qt-project.org for this, as well.
Good call. I just created one: bugreports.qt-project.org/browse/QTBUG-39529

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.