Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QML Loader loads components faster than property assignment



  • Hello QT users,

    I have been going through a problem that has been bugging me for two weeks now, and I cannot find a solution to this problem.

    I have my main window, which contains a loader. The loader loads a QML file that has a model in it, and when in the delegate of that model a button is pressed, I want to pass the model object directly to the loader. Then, using the same loader, I want to load another page that uses that passed model object and access its roles using the page.

    But whenever I do that, while the loader is set to asynchronous, it does not load. It complains that the model object is null. But, if I disable asynchronous, it works, but it still complains that the object is null. It's as though it loads it so fast, that the objects such as text that are bound to the model object are not loaded, but a few milliseconds later, it loads.

    Here is a modified version of my original code:

    main.qml

    ApplicationWindow {
    id: root
    property alias pageloader: testLoader;
    
         Loader {
         id: testLoader
         property QtObject modelData;
         asynchronous: true
         source: "./test.qml"
         }
    }
    

    test.qml:

    Item {
        id: test
    
         Repeater {
            model: testmodel
    
           delegate: {
                button {
                    id: testbtn
                    onClicked: {
                       root.pageloader.modelData = model;
                       root.pageloader.source = "./test2.qml"
                   }
                }
           }
         }
    }
    

    test2.qml

    Item {
         id: test2
    
         text {
            root.pageloader.modelData.title;
         }
    }
    

    TypeError: Cannot read property 'title' of null

    If I were to use the item property of the loader, it remains the same. The problem persists.

    Anyone has any idea how I can circumvent this issue? I tried passing the model object to the mainwindow (root), but the issue remains the same.

    The model I am using is a custom model, using QAbstractListModel. It works fine, no errors there. The loader is my only problem.


  • Moderators

    Guard the calls to pageLoader:

    Text {
            text: root.pageloader? root.pageloader.modelData.title : ""
         }
    

    Ugly, but works.


  • Moderators

    @Hamzan-Martinez Do not delete the topic, when someone took the time and effort to provide you with a working answer!


Log in to reply