PDA

View Full Version : How to add child items to QStandardItemModel?



TheIndependentAquarius
4th January 2021, 11:37
Greetings,

Idea is to have something like:

> File
.........New
.........Save
>Edit
.........Cut


I have:


int main( int argc, char *argv[] )
{
.........

QStandardItemModel model;

QStandardItem *parentItem0 = model.invisibleRootItem();


QStandardItem *file_item = new QStandardItem(QString("File"));


QStandardItem *new_ = new QStandardItem(QString("New"));

file_item->setChild(1, new_);


parentItem0 = file_item;


parentItem0->appendRow( file_item );

..........
}

This is not giving me anything.
What is the way to add child items to parent items?

d_stranz
4th January 2021, 16:52
From the QStandardItemModel docs:


An example usage of QStandardItemModel to create a tree:




QStandardItemModel model;
QStandardItem *parentItem = model.invisibleRootItem();
for (int i = 0; i < 4; ++i) {
QStandardItem *item = new QStandardItem(QString("item %0").arg(i));
parentItem->appendRow(item);
parentItem = item;
}

This code creates a tree that is 4 levels deep because each time though the loop the parent item pointer is replaced by the item just added:

item 0 -> item 1 -> item 2 -> item 3

This is basically what you want to do with your File -> New and File -> Save


This is not giving me anything.

Not surprising, because in Line 18 you reassign the parent item pointer to the file_item you just created, then tell that pointer to add itself as a child row of itself.

What you code needs to do is this:

0. Retrieve the invisible root item pointer.
1. Create the "File" item QStandardItem
2. Create the "New" item
3. Add it to the File item using add row
4. Create the "Save" item
5. Add it to the File item using add row
6. Add the File item to the root item using add row
7. Create the "Edit" item
8. Create the "Cut" item
9. Add it to the Edit item
10. Add the Edit item to the root item
etc.

You can change up the order of creation and addition of child items; that is, you can create the File item and add it to the root, then create the Edit item and add it to the root, then create the children of File and add them to the File item, etc. The important thing is to add each child to the correct parent, and never reassign the root pointer variable like you did in Line 18 of your code.

TheIndependentAquarius
5th January 2021, 13:42
Am thankful for your detailed response.