View Full Version : Need help Updating QTreeView model (QAbstractItemModel)

26th October 2009, 19:34
I can't get new data to show up in my QTreeView. I'm using Qt 4.5.
My application is a modified version of the "editabletreemodel" demo code.
I'm trying to insert more tree data at the root of the tree being displayed.

When the application starts up, a QTreeView is created with a TreeModel
(derived from QAbstractItemModel) which has no children. Everything looks
fine: column headers are properly displayed (which are retrieved from the
fields of the root element), etc.

When the user imports data, the file parser produces a tree of TreeItems.
To add this to the root of the tree being displayed by the TreeModel I created
the following method on TreeModel:

addAtRoot(TreeItem *moreData)
int position = rootItem->childCount();

QModelIndex modelIndex = createIndex(0, 0, rootItem);

beginInsertRows(modelIndex, position, position); // adding 1 thing
rootItem->insertChildItem(moreData, position);

The "insertChildItem()" method is implemented in the TreeItem class and does this:

void TreeItem::insertChildItem(TreeItem *item, int position)
item->parentItem = this;

childItems.insert(position, item);

Using the debugger, I can see that the tree of TreeItem objects available through the
TreeModel is properly updated. However, the QTreeView never displays the new data.

Any help would be appreciated.

Am I not constructing the right QModelIndex in addAtRoot()? Is there something
I need to do to notify the QTreeView besides calling (begin/end)InsertRows()?

One interesting item of note is that if I invoke the "insert row" function to create a new,
(blank) item, it gets a sizeways "T" line rendering instead of an "L" shaped
line in the heirarchy view. This tells me that at least part of the QTreeView
knows there was data added.

If I replace the call to addAtRoot() with a call to insertRows() I can create a
new (empty) item in the tree which is displayed properly.

To try and debug this, I changed the code so that the TreeModel isn't created
and associated with the QTreeView until the file is imported. This exercised
the TreeItem "insertChildItem()" method, but not the TreeModel "addAtRoot()"
method. The result worked fine. It limits the user to a single input file,
which isn't acceptable for my application.

26th October 2009, 23:49
You surely shouldn't use createIndex() here... Seems that you should pass an invalid index there. If it works then it could mean that your QAbstractItemModel::parent() implementation is wrong so be sure to check that one as well. Although on the other hand you're trying to pass valid parameters to createIndex() which is also wrong. If you're adding at the root, you should pass an invalid index (i.e. createIndex(-1,-1,0) if at all but it's easier to simply pass QModelIndex()).