QtQuick dynamic object in a different context
Asked Answered
E

1

2

In my qml I'm creating a C++ component object but can't figure out how to reference the object once it's created.

Here's the qml to create an OgreScene object:

MouseArea
{
    anchors.fill: parent

    function scene()
    {
        var scene = Qt.createQmlObject( "import Client.Plugin.Ogre 0.1; OgreScene{ id: pluginScene; engine: OgreEngine }", plugin );
        console.log( "qml: init scene" );
        pluginScene.init();
    }

    onClicked: scene()
}

When I run it I get:

Qt Debug: qml: init scene
Qt Warning: qrc:///client.qml:118: ReferenceError: pluginScene is not defined

I added this to the inline qml:

import Client.Plugin.Ogre 0.1; 

It cannot find the object definition without an import. This import had already been done in the qml file so it appears the inline qml is in a separate context from the file it's executed from.

How can I create a c++ component object in the same context as my qml file?

Estranged answered 22/8, 2013 at 20:58 Comment(4)
Creating a QML object from a string is a bit like creating from a new QML file so it is normal to have to import your plugin again. See the documentation : qt-project.org/doc/qt-5.0/qtqml/…Varico
Thanks. Any idea how to get a reference to the created object? I set it's ID property but it's not visible.Estranged
> Looking at the doc there seems to be a third parameter that could be the expected identifier ? qt-project.org/doc/qt-5.0/qtqml/…Varico
I don't think so: "If filepath is specified, it will be used for error reporting for the created object"Estranged
E
2

I have a workable solution. Instead of trying to load the qml inline the loader item can be used to dynamically manage items.

Here's code to load an item in response to a mouse click:

MouseArea
{
    anchors.fill: parent
    function changePlugin()
    {
        // unload previously loaded plugin
        pluginLoader.sourceComponent = undefined;
        // load new plugin
        pluginLoader.sourceComponent = myPlugin;
    }
    onClicked: changePlugin()
}

Insert a definition of what you want to load, in the spot where you want to load it:

Component
{
    id: myPlugin
    YourCustomPlugin
    {
        // do initialization when the object is loaded
        // I call the init method of my plugin
        Component.onCompleted: init();
    }
}

Loader { id: pluginLoader; }
Estranged answered 23/8, 2013 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.