Qt AbstractItemModel removeRows and delete causing core
I have a custom AbstractItemModel implementation with the following to insert nodes
Code:
layoutAboutToBeChanged();
beginInsertRows(createIndex(p_parent->row(), 0, p_parent), start, end);
TreeNode* p_node = new TreeNode(p_parent, p_data);
p_parent->appendChild(start, p_node);
endInsertRows();
layoutChanged();
And to remove rows:
Code:
layoutAboutToBeChanged();
beginRemoveRows(createIndex(p_parent->row(), 0, p_parent), row, row);
p_parent->removeChildren(row, row+1, this);
endRemoveRows();
layoutChanged();
When removeChildren is called, for each node that is removed the following is done:
Code:
changePersistentIndex
(createIndex
(p_node
->row
(),
0, p_node
),
QModelIndex());
delete p_node;
This works. I can add nodes and remove nodes.
Terminology NOTE: I'm using "nodes" and "rows" interchangeably. Sorry for any confusion.
What doesn't work:
1. If a new row is inserted in front of a selected node. The newly
inserted node becomes selected. [This is not what I expect of want.]
2. If a row is selected and then later deleted, immediate core dump.
3. If mouse over a row that is deleted, immediate core dump.
If I don't delete p_node. Everything runs fine. But obviously that creates a memory leak.
What am I doing wrong?
For reference I'm using QT 5.0.2 on 64 bit linux.
Re: Qt AbstractItemModel removeRows and delete causing core
Have you tried without the layout change calls? That is usually not necessary when adding/removing rows or columns.
Cheers,
_
Re: Qt AbstractItemModel removeRows and delete causing core
If I don't make the calls to the layout functions the gui tree doesn't show changes to the model.
Re: Qt AbstractItemModel removeRows and delete causing core
Bump.
I'd really like to solve this problem.
I don't know what I'm doing wrong.
The only way I've been able to create a working solution is to use QStandardItemModel and QStandardItem. But that item based approach is not suited to my problem and working that way is unnatural and just wrong. My data is row based NOT item based. My number of columns will never change. A cell of data (an item) by itself simply cannot exist in my application.
I've tried in 2 different custom implementations to just call beingInsertRows and endInsertRows but it never works (no rows are added or removed from the view). It only works when I call the layoutchange methods. And I read somewhere (stackoverflow I think) that I need to update the persistent indexes when I remove rows. So I'm doing that as well.
I feel like I'm doing so much work just to add/remove a row. Shouldn't the persisted indexes update on their own? Shouldn't the selected row remain selected when I insert a new row, rather than me having to do additional work to update yet another set of indexes somewhere?