QtQuick dynamic object in a different context

时光毁灭记忆、已成空白 提交于 2019-12-10 10:56:43

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18390703/qtquick-dynamic-object-in-a-different-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!