Rudolf Meijering
Rudolf Meijering

Reputation: 1587

Creating custom qml objects instances with Qt.createQmlObject()

I've got a custom QML object called Target.qml. I would like to create dynamic instances of this object using Qt.createQmlObject().

It works when using builtin qml objects like Image:

var newTarget = Qt.createQmlObject('import Qt 4.7; Image {source: "widgets/SlideSwitchImages/knob.png"; }', parent);

But fails when using any custom object types like:

var newTarget = Qt.createQmlObject('import Qt 4.7; Target {}', parent);

If however I use my custom Target type statically in QML everything works. Is this a known limitation, any workarounds?

Upvotes: 4

Views: 8241

Answers (2)

blakharaz
blakharaz

Reputation: 2590

If you just need an arbitrary number of Target instances it would be better to use Component.

Component {
    id: targetFactory
    Target {}
}

var newTarget = targetFactory.createObject(parent, properties)

However if you want to stick to the Qt.createQmlObject call I guess you have the Target component in a different directory and you're just missing out some import statement. The string parameter must be the content of a QML file that works on its own in the same directory as the one calling it.

E.g.

var newTarget = Qt.createQmlObject('import QtQuick 1.0; import "../Targets"; Target {}', parent);

BTW: The Qt 4.7 imports are deprecated because they don't allow additional versions of QtQuick.

Upvotes: 5

sam-w
sam-w

Reputation: 7687

From the docs:

There are two ways to create objects dynamically from JavaScript. You can either call Qt.createComponent() to dynamically create a Component object, or use Qt.createQmlObject() to create an item from a string of QML. Creating a component is better if you have an existing component defined in a .qml file, and you want to dynamically create instances of that component. Otherwise, creating an item from a string of QML is useful when the item QML itself is generated at runtime.

I understand this to mean that createQmlObject will only work if you've defined the item type at runtime and that the application is therefore aware of the existence of it.

createComponent seems to perform the same function but for item types pre-defined in .qml files, as in your case.

Upvotes: 1

Related Questions