Search code examples
c++qtqmlopenstreetmapqtlocation

QML: How to correctly pass property to PluginParameter value from C++ code?


Hello everyone!

I've got the problem with passing property value through C++ to QML. My project is desktop application that must works with maps under Windows. So, after reading docs I found the best solution via QML using Qt Location. I chose OSM Plugin.

Everything works good but I need to manually locate cache into custom directory. So for that I want to pass such property (cachePath) value from C++ code to QML.

Part of C++ code:

QQuickView *view = new QQuickView;
view->rootContext()->setContextProperty("cachePath", "C:/111/");
view->setSource(QUrl(QStringLiteral("qrc:/qml/OSMView.qml")));

Important part of QML code:

Map
{
    zoomLevel: 10

    plugin: Plugin
    {
        name: "osm"
        PluginParameter { name: "osm.mapping.highdpi_tiles"; value: true }
        PluginParameter { name: "osm.mapping.offline.directory"; value: cachePath }
        PluginParameter { name: "osm.mapping.cache.directory"; value: cachePath }
    }

    <... nevermind ...>
}

So debug said that everything alright and property is passed. But there is no new tiles after work with maps in this custom directory.

But, if I type manually value: "C:/111/" - everything works fine and directory is replenished with new cache tiles.

What could be the problem?

Thanks for advance!


Solution

  • If someone interesting you can solve problem like this:

    C++ side:

    QVariantMap params
    {
        {"osm.mapping.highdpi_tiles", YOUR_CUSTOM_VALUE},
        {"osm.mapping.offline.directory", YOUR_CUSTOM_VALUE},
        {"osm.mapping.cache.directory", YOUR_CUSTOM_VALUE}
    };
    
    QQuickView *view = new QQuickView;
    view->setSource(QUrl(QStringLiteral("qrc:/qml/OSMView.qml")));
    QObject *item = (QObject *) view->rootObject();
    QMetaObject::invokeMethod(item, "initializePlugin", Q_ARG(QVariant, QVariant::fromValue(params)));
    

    QML side:

    Item
    {
        id: osmMain    
        property variant parameters
    
        function initializePlugin(pluginParameters)
        {
            var parameters = new Array;
            for(var prop in pluginParameters)
            {
                var parameter = Qt.createQmlObject('import QtLocation 5.6; PluginParameter{ name: "'+ prop + '"; value: "' + pluginParameters[prop] + '"}', map)
                parameters.push(parameter)
            }
            osmMain.parameters = parameters
            map.plugin = Qt.createQmlObject('import QtLocation 5.6; Plugin{ name: "osm"; parameters: osmMain.parameters }', osmMain)
        }
    
        Map { id: map <...> }
    
    <...>
    
    }