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

Dynamically create inline Component



  • I would like to know if its possible to instantiate an inline Component via createObject() as with regular Component.

    Example code:

    Item {
        id: root
        component MyText: Text {
            font.pixelSize: 50
        }
    
        Component.onCompleted: {
            // This does not work
            MyText.createObject(root)
        }
    }
    


  • I think I found a workaround, at least:

    Component {
        id: cmpt
        MyText {}
    }
    component MyText: Text {
        font.pixelSize: 50
    }
    


  • Start with a Loader, Repeater, Instantiator, and then if those don't do what you want, look into creating objects by script. Most of the time the first 3 will suffice.



  • I hadn't noticed the addition of the component keyword. Thanks for pointing it out.

    The syntax I've used previously is:

    Item {
        property Component myComponent: Text { ... }
    
        Component.onComplete: myComponent.createObject()
    }
    

Log in to reply