[solved] Dynamically adding items



  • I want to dynamically add items to a custom component when it's created. According to
    http://qt-project.org/doc/qt-4.8/qdeclarativedynamicobjects.html , I can do this by creating an external JavaScript file,

    @
    import "MyNavDrawer.js" as Scripts;
    @

    and call it from onCompleted:

    @
    Component.onCompleted: { Scripts.createItems(); }
    @

    My JavaScript file looks like this:

    @
    var listViewComponent;

    function createItems()
    {
    console.log ("createItems");

    listViewComponent = Qt.createComponent ("MyNavDrawerListView.qml");
    
    if (listViewComponent.status === Component.Ready)
    {
        console.log ("ready");
        createItemsFinish();
    }
    else
    {
        console.log ("delayed");
        listViewComponent.statusChanged.connect (createItemsFinish);
    }
    
    console.log ("end of createItems");
    

    }

    function createItemsFinish()
    {
    console.log ("createItemsFinish");

    if (listViewComponent.status !== Component.Ready)
    {
        console.log ("createItemsFinish: Component still not ready! " + listViewComponent.errorString());
        return;
    }
    
    for (var i = 0; i < items.length; i++)
    {
        console.log (items[i].caption);
        var v = listViewComponent.createObject (drawerFrame, { "data": items[i] });
    
        if (v === null)
        {
            console.log ("createItemsFinish: Failed to create item " + i + "!");
            return;
        }
    

    }
    }
    @

    createItems is in fact called, but the signal handler createItemsFinish isn't. The log output is:

    @
    qml: createItems
    qml: delayed
    qml: end of createItems
    @

    What am I doing wrong?


  • Moderators

    Hi,

    Are you sure MyNavDrawerListView.qml can be found? Add this line to the end of createItems():

    @
    console.log(listViewComponent.status)
    @

    Compare the result with http://qt-project.org/doc/qt-5/qml-qtqml-component.html#status-prop



  • Oops, you're right! The status is 3 (Component.Error), and the errorString showed there was an error in the qml file I was trying to load. Thanks for the hint!


Log in to reply
 

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