Object created from C++, display on QML side and delete from C++



  • Hi,

    Once my QML page finished to load I need to call a C++ function that will produce a model (list of item).
    Once the QML page is destroy, (ex : changing page), I want to free the object that has been allocated on the C++ side.

    The C++ side need to keep the ownership of the model has an engine can alter the list at any time. If the ownership is going to the QML side I would need a mechanism to detect when the list is going to be destroyed and stop updating it but I found this way more complicated.

    Here is an exemple of what I have yet :

    C++ Side :

    void CUIManager::createList(QQuickItem* pQuickItem)
    {
        CMyList* p = new CMyList(this);
        p->addItem(...);
        p->addItem(...);
        pQuickItem->setProperty("model", QVariant::fromValue(p));
    }
     
    void CUIManager::removeList(QQuickItem* pQuickItem)
    {
        CMyList* p = (CMyList *)pQuickItem->property("model");
        delete p; // I'm getting this compilation error : cannot convert from 'QVariant' to 'CMyList *'
    } 
    

    QML side :

        GridView {
            id : sectionMainMenuGrid
            Component.onCompleted: {
                uiManager.createList(sectionMainMenuGrid);
            }
    
            Component.onDestruction: {
                uiManager.removeList(sectionMainMenuGrid);
            }
        }
    

    By the way, is my reasoning is correct ? I'm open to any suggestions.

    Best regards,



  • Nevermind, I got it :)

    void CUIManager::removeList(QQuickItem* pQuickItem)
    {
         QVariant q = pQuickItem->property("model");
         CMyList* pMyList = (CMyList*)q.value<void *>();
         delete pMyList;
    } 
    

    Hope it will help someone else



  • Hi

    Why not just save pointer of allocated model?
    Also, consider to register the pointer at quick engine as CPP, other wise it might be destroed by JS GC in an inappropriate time

    br


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.