Take the 2-minute tour ×

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?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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.


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.

share|improve this answer
Hi thanks for the suggestion of the component factory, I will use that next time. I did indeed miss the import statement in my qml string. It seems like createQmlObject has it's own scope. –  Rudolf Meijering Nov 30 '11 at 9:10
add comment

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.

share|improve this answer
Hi thanks for the answer. I have defined the type at runtime and can use it within static qml like an other type, it seems however that the createQmlObject method has it's own scope and therefore require their own import statement as part of the string. –  Rudolf Meijering Nov 30 '11 at 9:12
add comment

Your Answer


