Question

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
    //createPoly(polyGenerator);

    var component = Qt.createComponent("Rectangle");
    console.log(component.status + " " + Component.Null);
    if (component.status == Component.Ready) {
        createPoly(component);
    } 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());
                return;
            }
            createPoly(component);
        });
    }
}

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});

    map.addMapObject(poly);
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top