0
votes

QML allows us to structure our apps very well into Modules and then import them whenever needed into our application. This makes sense, especially since we just have to work with namespaces and not with URIs / paths.

However when I want to create a QML Component dynamically, I can only load it from a URI / path. For example:

var myComponent = Qt.createComponent("./qml/Button/Button.qml");

To me, this seems to contradict very much with Qt / QML's philosophy of working with Namespaces instead of URIs / paths.

Why is it not possible to do the following:

import QtQuick 2.4
import com.MyCustomStuff 1.0   // <-- contains my custom Button

...

function createMyObj(){
    return Qt.createComponent(Button);
}

I would very much appreciate any explanation from our Qt Experts! Thanks!

2

2 Answers

0
votes

You can't do that cause createComponent take only a string, you should use createObject. use this aproach:

ComponentCreator.qml

    import QtQuick 2.2

    Item {
        id:idRoot
        // take the component that you want to create
        property Component component
// reference to the created object, with that property you can 
// access all properties of the created component, like I am doing in the Component.onCompleted in my main.qml 
        property Item createdObject
        function createMyObj(component){
            createdObject = component.createObject(idRoot);
        }
        onComponentChanged:{
            createMyObj(component)
        }

    }

main.qml

import QtQuick 2.2
import QtQuick.Controls 1.2
Item {
    width:800
    height: 480
    ComponentCreator{
        id:idCompCreator
        component: Button{}
    }
Component.onCompleted: idCompCreator.createdObject.width = 100
}
0
votes

I've never tried it, for I used to use the path based approach you mentioned, and I've not my laptop to test it now, but I guess you can follow the other approach using the import as above, then defining something like Component { id: myComponent; Button { } }, thus using it with myComponent.createObject.

From the [documentation][1], createObject is a method of any Component indeed, so it should work.

Anyway, the approach using Qt.createComponent doesn't look to me as it contradicts the philosophy, as usually I use it with a qrc: string that perfectly adheres to that philosophy, doesn't it?

Let me know if it solves the problem, I'll be able to have a try in the evening, for I'm far from my laptop the whole day.

It follows an example:

com.MyCustomStuff 1.0

YourContainer {
    id: container

    // your code

    function createButton() {
        var bt = buttonComponent.createObject(container);
        // do whatever you want from now on :-)
    }

    Component {
        id: buttonComponent
        Button { }
    }
}