PDA

View Full Version : QPersistentModelIndex and QDataWidgetMapper



Banjo
1st July 2008, 01:59
Hi

I am using a QDataWidgetMapper with a QSqlRelationalTableModel (Manual edit strategy). When a row is inserted into the model, I want the datawidgetmapper to display that row after it is saved to the database. I understand that when a row is inserted into the model, the model indexes are invalid and so I have been looking at using a QPersistentModelIndex to hold the index of the new row. The problem that I am having is that the persistent index appears to be invalid after model.submitAll.

sample code:

row = self.detailMapper.currentIndex()
persistentIndex = QPersistentModelIndex(self.model.index(row,0))
self.detailMapper.submit()
self.model.submitAll()
self.detailMapper.setCurrentIndex(persistentIndex)

Is this the right approach and how do I use persistent model indices correctly. I have looked at the documentation and posts on this forum but am not able to solve my problem.

Thanks in advance

wysota
1st July 2008, 07:34
The persistent index will become invalid after the model is being refreshed (and that's what happens to the sql model after data is submitted to the database). The only thing you can do is to remember the primary key of the item and reselect it after the commit.

Banjo
2nd July 2008, 00:07
Thanks for that.
In what cases then would you use a PersistentModelIndex??

wysota
2nd July 2008, 00:24
When you edit a model - in that case if you insert rows inbetween other rows, persistent indexes will make sure they still point to the same rows than before the insert. Unfortunately they become invalid when you reset the model (and that's what happens after you commit changes to the database).

Banjo
2nd July 2008, 01:34
OK thanks.

I am using a QSqlRelationalTableModel and a QDataWidgetMapper. What is the best way to manage transactions?

wysota
2nd July 2008, 07:24
Your model is a subclass of QSqlTableModel that has a QSqlTableModel::database() member which gives you access to the database that in turn has methods called QSqlDatabase::transaction(), QSqlDatabase::rollback() and QSqlDatabase::commit().

Banjo
3rd July 2008, 00:31
Thanks again for that.