Creating QML Item via function defined in js file, and inserting that item into layout, doesn't show the item



  • Note: the function in QtQuickUtils.js in the following testcase is just to abstract away the boilerplate involved in creating a QML object from a component URL.

    Testcase:

    main.qml:

    import QtQuick 2.6
    import QtQuick.Window 2.2
    import QtQuick.Layouts 1.3
    import "QtQuickUtils.js" as QtQuickUtils
    
    Window {
        visible: true
        width: 640
        height: 480
    
        GridLayout {
            anchors.fill: parent
            id: container
            columns: 1
        }
    
        Component.onCompleted: {
            QtQuickUtils.createObjectFromComponent("qrc:///MyItem.qml", container, {
                "Layout.fillWidth": true, "Layout.fillHeight": true
                // "width": 100, "height": 100
            });
        }
    }
    

    MyItem.qml:

    import QtQuick 2.0
    
    Rectangle {
        color: "red"
    }
    

    QtQuickUtils.js:

    .import QtQml 2.0 as Qml
    .pragma library
    
    function createObjectFromComponent(componentUrl, parent, properties) {
        var component = Qt.createComponent(componentUrl);
        function finishCreation() {
            console.log("finishCreation");
            if (component.status === Qml.Component.Ready) {
                var obj = component.createObject(parent, properties);
                if (obj === null) {
                    console.log("Error creating object");
                    return;
                }
                console.log("success in creating obj");
            } else if (component.status === Qml.Component.Error) {
                console.log("Error loading component:", component.errorString());
                return;
            }
        }
        if (component.status === Qml.Component.Ready) {
            finishCreation();
        } else {
            component.statusChanged.connect(function() { finishCreation(); });
        }
    }
    

    This shows nothing (but "finishCreation" and "success in creating obj" are printed).

    If I comment out the "Layout.fillWidth": true, "Layout.fillHeight": true line and uncomment the one after that, the item is displayed.

    Also if I move the function from the JS file to main.qml, the item is displayed.

    Any idea what I'm doing wrong, and a proper fix?



  • Try specifying the width and height inside myitem.qml



  • Thanks but I got a working answer here.


Log in to reply
 

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