Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Is it ok? - QStandardItemModel and ownership of item



  • Hi,

    A few weeks ago I ask:

    Have I delete qstandarditem when I setItem() in QStandardItemModel. I get answer:

    "The model owns the items and will delete them so no manually deleting is needed."

    And docs:
    https://doc.qt.io/qt-5/qstandarditemmodel.html#setItem

    Sets the item for the given row and column to item. The model takes ownership of the item. If necessary, the row count and column count are increased to fit the item. The previous item at the given location (if there was one) is deleted.
    

    Ok. So I check It:

        for(auto text: itemsText)
        {
            QStandardItem *item = new QStandardItem(text);
            wek.append(item);
            qInfo()<<item<<item->parent()<<"before";
            itemModel->setItem(itemModel->rowCount(),0,item);
            qInfo()<<item<<item->parent()<<"after";
        }
    

    wek is the vector of QStandardItems *. I get texts:

    0x2e9d780 0x0 before
    0x2e9d780 0x0 after
    0x2e9d400 0x0 before
    0x2e9d400 0x0 after
    0x2e9d4e0 0x0 before
    0x2e9d4e0 0x0 after
    

    I check wek after setModel() in QComboBox:

    setModel(itemModel);
        for(auto x:wek)
            qInfo()<<x<<x->parent();
    

    I get:

    0x2e9d780 0x0
    0x2e9d400 0x0
    0x2e9d4e0 0x0
    

    And my question: Are parents ok? I get 0x0 and when I read doc I think I should get parent = itemModel. Is it ok?


  • Lifetime Qt Champion

    Ownership and qobject parent / child relationship are two similar but different things. Just because an object takes ownership of another object there is not need that one is the parent of the other.


  • Lifetime Qt Champion

    Ownership and qobject parent / child relationship are two similar but different things. Just because an object takes ownership of another object there is not need that one is the parent of the other.


Log in to reply