2016-07-26 34 views
3

我動態實例化的對象在main(),並將其設置在諸如上下文:如何銷燬QML中的上下文指針?

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

至此我沒有訪問該指針在C++只是在QML後。在應用程序結束時,我想釋放指針(更具體地在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什麼都不做。

我搜查了文檔,但找不到我在找的東西。任何人有任何想法?謝謝!

+0

請閱讀[此](http://doc.qt.io/qt-5/qtqml-cppintegration-data.html#data-ownership)和[此](HTTPS://wiki.qt .io/Shared_Pointers_and_QML_Ownership)鏈接。 – folibis

回答

0

您可以嘗試使用智能指針,以便在超出範圍時將其銷燬。

//main.cpp 

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