Take the 2-minute tour ×

I'm trying to create an instance of a QtMobility MapPolyline and several of Coordinate in QML programmaticaly from a Javascript function.

As far as I can see the only way to create new instance from Javascript functions is to use Qt.createComponent and Qt.createQmlObject. However, I can't find a way to call createComponent that will work (I always get a file doesnt exist error). And I'd like to avoid Qt.createQmlObject since it seems like a really bad practice.

Is there any clean way to achieve this?

Component {
    id: polyGenerator
    MapPolyline {}

function addPoly() {
    //This next line works, but crashes when trying to add positions

    var component = Qt.createComponent("Rectangle");
    console.log(component.status + " " + Component.Null);
    if (component.status == Component.Ready) {
    } else if (component.status == Component.Error) {
        console.log("Error: " + component.errorString());
    } else {
        component.statusChanged.connect(function () {
            if (component.status == Component.Error) {
                console.log("Error: " + component.errorString());

function createPoly(component) {
    var poly = component.createObject(map);

    poly.border.color = "red";
    poly.border.width = 4;

    // I get a crash here, my guess is that I need proper Coordinate objects
    poly.addCoordinate({latitude: -34.60553, longitude: -58.38088});
    poly.addCoordinate({latitude: -34.60720, longitude: -58.38081});
    poly.addCoordinate({latitude: 34.60720, longitude: -58.38081});
    poly.addCoordinate({latitude: -34.60597, longitude: -58.37930});

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Qt.createComponent needs a URL to load a file from. That's why it complains about a missing file; you're trying to load a file called "Rectangle".

If you just want to create objects dynamically create your component declarative.

Component {
    id: component
    Rectangle {

That way the createPoly function should work fine.

share|improve this answer
Yes, I'm aware that it takes a URL. However, since my objective is to instance a QtMobility item, I don't know the url. The example code is the product of several iterations of trying to get it to work, and the Rectangle bit was just a test, I know it's not supposed to work. –  Juan Dec 16 '11 at 4:16
It seems this is the accepted way of doing this, so I'll accept the answer. Thanks for your answer! –  Juan Dec 17 '11 at 2:31
add comment

Your Answer


