QtQuick动态对象在不同的​​上下文中 [英] QtQuick dynamic object in a different context

查看:195
本文介绍了QtQuick动态对象在不同的​​上下文中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的qml中,我创建了一个C ++组件对象,但是无法找到如何引用创建后的对象。

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

这里是qml创建一个OgreScene对象:

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

当我运行它我得到:

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

import Client.Plugin.Ogre 0.1; 

在没有导入的情况下找不到对象定义。这个导入已经在qml文件中完成了,因此它显示的内联qml是在一个单独的上下文中执行的文件。

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.

如何创建一个c ++组件对象与我的qml文件在同一上下文中?

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

推荐答案

我有一个可行的解决方案。

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

这篇关于QtQuick动态对象在不同的​​上下文中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆