Search code examples
c++qtqtreeviewqstandarditemmodelqstandarditem

how to append a QStandardItem into two rows


What I want to have is:

Root ------ item1
     |         --- newItem
     |_____ item 2
     |         --- newItem
     |_____ item 3

Here is the code:

QStandardItem *item1 = new QStandardItem(QString("item1"));
QStandardItem *item2 = new QStandardItem(QString("item2"));
QStandardItem *item3 = new QStandardItem(QString("item3"));

QStandardItem *rootNode = standardModel->invisibleRootItem();

rootNode->appendRow(item1);
rootNode->appendRow(item2);
rootNode->appendRow(item3);

QStandardItem *newItem = new QStandardItem(QString("newItem"));

item1->appendRow(newItem);
item2->appendRow(newItem);

when it is run, I see the newItem is appended on item1 without any problem. However, on the second one (item2), the newItem is appended but as a blank item.

what is wrong with it?

EDIT: Here is a printscreen of what I meant. newItems appear on the first row (QStandardItem),but blank on the second row.

enter image description here


Solution

  • When you append the item to the first row, it gets a parent and you can not add it to another row. You should append a copy of the item :

    QStandardItem *newItem = new QStandardItem(QString("newItem"));
    
    item1->appendRow(newItem);
    item2->appendRow(newItem->clone());