Using a Loader for a string of QML



  • I've been using the Loader QML element for loading screens. 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.
        }
    }@


  • A few things that might help:

    It wasn't obvious to me that you can create a custom qml object just using qml in a text file. Create a qml file to define your object in the same directory as the code that calls it. The file name sets the qml object's name.
    It's very similar in effect to inheritance in C++.

    I think your creation code should be more like this:

    @ // dynamic object creation
    component = Qt.createComponent( qmlFileName );
    if ( component.status == 3 ) // enumeration 'Component.Error' == 3
    {
    // Error Handling
    console.log("Error loading component:", component.errorString());
    }
    else
    if ( component.status == 1 ) // enumeration 'Component.Ready' == 1
    finishCreation();
    else
    component.statusChanged.connect( finishCreation );@

    here's the function it references:

    @function finishCreation()
    {
    if ( component.status == 1 ) // enumeration 'Component.Ready' == 1
    {
    var disp = component.createObject( _rootItem, { "parent": _rootItem } );
    if (disp == null)
    {
    // Error Handling
    console.log( "Error loading plugin into display area" );
    }
    }
    else
    if ( component.status == 3 ) // enumeration 'Component.Error' == 3
    {
    // Error Handling
    console.log("Error loading component:", component.errorString() );
    }
    }
    @

    Note that this code sets the VISUAL parent of the created item. If you don't then inheriting parent properties doesn't work


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.