如何破坏QML中的上下文指针?

时间:2016-07-26 09:11:48

标签: qt pointers qml qtquick2

我在main()中动态实例化一个对象,并将其设置在上下文中:

 Controller *controller = new Controller();
 engine.rootContext()->setContextProperty("controller", controller);

在此之后,我无法在QML中访问c ++中的指针。在应用程序结束时,我想释放指针(在Component.onDestruction中更具体)。我无法弄清楚如何在QML中做到这一点。

  1. 我尝试了controller.destroy(),但它返回:Error: Invalid attempt to destroy() an indestructible object

  2. 还尝试controller.deleteLater(),但它给了我:TypeError: Property 'deleteLater' of object Controller(0x4914028) is not a function

  3. delete controller什么都不做。

  4. 我搜索了文档,但无法找到我要找的内容。任何人有任何想法?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试使用智能指针,以便在超出范围时将其销毁。

//main.cpp

QSharedPointer<Controller> controller =
    QSharedPointer<Controller>(new Controller(), &QObject::deleteLater);
engine.rootContext()->setContextProperty("controller", controller);
相关问题