anio
anio

Reputation: 9171

Qt AbstractItemModel removeRows and delete causes core

I have the following to insert nodes:

  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:

  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:

 changePersistentIndex(createIndex(p_node->row(), 0, p_node), QModelIndex());
 delete p_node;

It 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.

Upvotes: 3

Views: 1482

Answers (3)

kikeenrique
kikeenrique

Reputation: 2669

To fix crashes you should use deleteLater instead of delete, so your view won't die trying to access invalid objects.

Selected item seems a index problem. Looks like it's missing a notification to view.

Upvotes: 1

trompa
trompa

Reputation: 2017

Do append and remove children methods update the rowCount?

It seems to be the problem.

Check how is done in QStandardItemModel

Updating rowcount should solve the 3 points without having to update the persistent indexes:

  1. If rowcount is not updated, is normal that selected item changes to the inserted before, its where the index is pointing.
  2. & 3. Indexes are pointing to a deleted item.

Upvotes: 1

Zaiborg
Zaiborg

Reputation: 2522

to point 1: maybe

model->blockSignals(true);
...
model->blockSignals(false); 

will fix that selection behaviour.

i guess selected indexes/rows will have some functions called from the framework. so if they are deleted, they cause the crash. if you want to delete them, set the selection to another row/index and it should run fine ... '

if you mouse over a deleted row' ... if the row should be just empty, why not set the text empty?

Upvotes: 0

Related Questions