When I intended to write a small code using QTreeView and QStandardItemModel.
I encountered a problem.

When I made a grandchild item, using QStandardItemModel::insertRow(int row, const QModelIndex & parent = QModelIndex()),
the item did not appeared in the tree view.

In the following code, Case1 worked good.
But, contrary to my expectation, Case2 did not work.

Is it correct to make a grandchild item, using QStandardItemModel::insertRow() ?

Qt Code:
  1. #include <QtGui/QApplication>
  2. #include <QtCore/QModelIndex>
  3. #include <QtGui/QStandardItem>
  4. #include <QtGui/QStandardItemModel>
  5. #include <QTreeView>
  6. #include <QtDebug>
  7.  
  8. int main(int argc, char *argv[])
  9. {
  10. QApplication application(argc, argv);
  11.  
  12. QTreeView treeView;
  13. treeView.setModel(&model);
  14.  
  15. // (Case 1)
  16. // QStandardItem* rootItem = model.invisibleRootItem();
  17. // rootItem->insertRow(0, new QStandardItem("Child Item"));
  18. // QStandardItem* childItem = rootItem->child(0, 0);
  19. // if (childItem)
  20. // childItem->insertRow(0, new QStandardItem("Grandchild Item"));
  21.  
  22. // (Case 2)
  23. model.insertRow(0, new QStandardItem("Child Item"));
  24. QModelIndex childItemIndex = model.index(0, 0, QModelIndex());
  25. bool isSuccess = false;
  26. if (childItemIndex.isValid()) {
  27. isSuccess = model.insertRow(0, childItemIndex); // make a grandchild, but the item does not appear
  28. }
  29. qDebug() << "isSuccess : " << isSuccess; // true
  30.  
  31. childItemIndex = model.index(0, 0, QModelIndex());
  32. qDebug() << "childItemIndex.isValid : " << childItemIndex.isValid(); // true
  33. QModelIndex grandchildItemIndex = model.index(0, 0, childItemIndex);
  34. qDebug() << "grandchildItemIndex.isValid() : " << grandchildItemIndex.isValid(); // false
  35.  
  36. treeView.show();
  37.  
  38. return application.exec();
  39. }
To copy to clipboard, switch view to plain text mode 

I'm sorry in poor English.