Search code examples
qtqmlqt5dynamic-allocation

Possible to load built in QML components dynamically using Component.createComponent()


I want to add fonts to my application using the FontLoader QML component.

My first thought was to use a Repeater, but it only supports Item derived delegates, which FontLoader is not.

Then, my next thought was to dynamically create FontLoaderQML components using the Component::createComponent(url) function, but what url should I use here? Is it possible to dynamically create built in QML components without providing the url to the qml file in QT_INSTALL_DIR?

Side notes: I know it's possible if I subclass FontLoader, but I want to avoid the extra code if possible.

I also know that it's possible to use the Component::createQmlObject() to create a component from a string, but I really do not want to do that.


Solution

  • Instead of Repeater you could use an Instantiator, it allows you to dynamically create objects even if they are not Itemss.

    If you still wanted to do it imperatively, you have to use Component :

    Component {
        id: fontLoaderComponent
        FontLoader {}
    }
    //...
    fontLoaderComponent.createObject(parent, {name : "Courier"}); //use it like this to create a new FontLoader