How to add child nodes to TreeView after construction?
-
Hi,
I am using Qt 5.9 on linux. I have the Simple Tree Model Example running in my app, but now I'd like to add child nodes to the TreeView after the initial model has already been constructed. The only thing I've changed from the example is that the data is supplied by an external source rather than how it does it internally.
Can anyone provide suggestions on how to add child nodes after construction of the model?
-
Works with any model adhering to the
QAbstractItemModel
interface:const QModelIndex parent = model->index(0,0); // get the item in the first row and first column model->insertRow(0,parent); // add 1 child row model->insertColumn(0,parent); // add 1 child column model->setData(model->index(0,0,parent),QStringLiteral("Child Item")); // set the data of the child
-
-
This is a bit confusing because from the Simple Tree Model Example I used, my initial construction appears like the following ...
QList<QVariant> rootData; rootData << "Col 1" << "Col 2"; MyTreeItem *parentItem = new MyTreeItem(rootData); QList<QVariant> a_data; a_data << "Item1" << "data1"; MyTreeItem *a_item = new MyTreeItem(a_data, parentItem); parentItem->appendChild(a_item); QList<QVariant> b_data; b_data << "Item2" << "data2"; MyTreeItem *b_item = new MyTreeItem(b_data, parentItem); parentItem->appendChild(b_item); treeModel = new MercuryTreeModel(parentItem); treeView->setModel(treeModel);
Using the above, I create a new MyTreeItem and pass in the parent node at the time of creation. But using the index, insertRow, and setData methods, I'm not seeing how that would work.
Can someone elaborate?
-
I've changed things up a bit, but now having trouble adding my class to the setData function.
The MyTreeItem class does not inherit QObject.
class MyTreeItem { // ... }; Q_DECLARE_METATYPE(MyTreeItem)
I'm trying to add an item to my treeview, but not sure how to construct this class with QVariant.
// ... QList<QVariant> name; name << new_name << ""; const QModelIndex parent = treeModel->index(0, 0); MyTreeItem *newItem = new MyTreeItem(name); treeModel->insertRow(0, parent); treeModel->setData(treeModel->index(0, 0, parent), QVariant(newItem));
I get the following error ...
error: use of deleted function ‘QVariant::QVariant(void*)’ treeModel->setData(treModel->index(0, 0, parent), QVariant(newItem));
Can anyone help w/ that?
-
Why would you set a pointer to a QTreeItem as data of another QTreeItem?
See https://doc.qt.io/qt-5/qtreewidgetitem.html#details on how to set a QTreeWidgetItem as a child of another QTreeWidgetItem