View Full Version : beginInsertRows() beginRemoveRows()

22nd October 2014, 22:57
This probably sounds like a simpleton question but...

Every example I have seen, including the abstractitemmodel which is included with QtCreator does the following:

beginInsertRows(QModelIndex(), rowCount(), rowCount());

On a very first call I guess a QModelIndex does have to be created, however, the example repeatedly calls this method:

model.addAnimal(Animal("Wolf", "Medium"));
model.addAnimal(Animal("Polar bear", "Large"));
model.addAnimal(Animal("Quoll", "Small"));

I'm asking because, while it "seems" to work, it 'duth maketh no senseth'. Why? Because, it would seem to me, one should be using the same index between the view and the model.

I'm asking because I'm currently writing an application which "periscopes" over a large database showing only a few rows at a time in the view. I am adding and deleting rows in my model all of the time. It would seem creating a new QModelIndex() each time I insert/remove rows should send things into a stack dump situation at some point.

Are all of these examples just really bad or am I missing something in the documentation?:confused:


23rd October 2014, 08:56
I don't see the relation between beginInsertRows and your question. QModelIndex is a short lived object that can be repeatedly created and destroyed. Objects of this type are not stored anywhere and especially not in the model. If storing an index is required for some reason (e.g. to store the currently selected index in a view) then QPersistentModelIndex is used instead but you should avoid is use of possible as it is much heavier than its light cousin.

23rd October 2014, 20:28
Thank you.

The piece of information I was missing was the fact it is a short lived entity. For some reason I believed it was going to be the index for the entire model, not just the handful of rows I might be adding to the end of the model.

23rd October 2014, 23:07
The model index can be treated as an iterator or even a volatile pointer on an item in the model. It is not tied in any way with the actual physical data in the model. You are passing QModelIndex() to beginInsertRows() to note that you are adding nodes to top-most level of hierarchy in the model. If you wanted to add a child item to one of the existing items, you would first have to get an index of that existing item using QAbstractItemModel::index() and then pass that index to beginInsertRows().