Congratulations to our 2022 Qt Champions!

[Solved] Adding new items to model (MVC)

  • Hello!
    I've created my own model, that bases on Blanchet-Summerfield methon from all-known book.
    So, I have an Node object. Every Node has a pointer to parent node and a list of child node. Model has the "main Root Node", which parent == 0 ad child are the needed model's nodes.
    The "main Root Node" doesn't appear in view, only its nodes:

    @RootNode - invisible

    At first time I fill this model by data using beginResetModel and endResetModel functions.
    But there are cases, when I want to add a few nodes into the model, but don't want to reset it whole. Additionaly, I use a proxy sorting model.

    Reading Qt help I see that I should use beginInsertRows and endInsertRows functions. The problem is that functions have a QModelIndex parameter - parent node.
    I don't use QModelIndex at all!
    To know node class from QModelIndex presented I use this construction, as written in the book:

    @tUMClientsNode lNode = static_cast<tUMClientsNode>(aParent.internalPointer());@

    tUMClientsNode - my node class, aParent - QModelIndex.

    What should I do to get QModelIndex from my Node? How to use beginInsertRows correctly?

    To add a single item I use similar code now:

    @void tUMClientsModel::AddNewClient(tUMDCClientInfo &aNewClient, bool aUseBeginInsert)
    if (aNewClient.fClientParentID == 0)
    fRootNode->fChildrenList.append(new tUMClientsNode(fRootNode, aNewClient));
    for (int i = 0; i < fRootNode->fChildrenList.count(); i++)
    if (fRootNode->fChildrenList[i]->fClientInfo.fClientID == aNewClient.fClientParentID)
    new tUMClientsNode(fRootNode->fChildrenList[i], aNewClient)

    Here's full code of my model: "":

    Thank you!

  • To create a model index you need to know the column and row indexes of a certain item. Then you can:
    @createIndex(row, column, theItem);@
    where theItem is a pointer to the item the model index is for.

    I usually obtain the row index by searching through the children list in the parent node. This is probably best done by creating an index() function in the node class that does the search. Then you would probably get:
    @createIndex(theItem->index(), 0, theItem);@
    Makes sense?

    Also it would make sense to have the items themselves handle the insertions into the lists. You really want encapsulation here, or else your model will end up unreadable.

  • You might also want to read through the "Simple Tree Model example":

  • It works! It works!

    Thank you wery much!

Log in to reply