PDA

View Full Version : QSqlTableModel, how to recognize new records from dirty records



franco.amato
18th March 2022, 20:12
Hi,
In my project I am using a QtableView and a QSqlTableModel connected to a database table.

The view should be able to distinguish new inserted records from modified (dirty) records, because I need to apply 2 different background color.

Is it possible to do that?

Franco

franco.amato
19th March 2022, 14:26
It seems that's not possible

d_stranz
19th March 2022, 15:18
It seems that's not possible

If you have derived your own model from QSqlTableModel, then I assume you are using data() and setData() to modify the database. If you haven't derived your own class, then do so and reimplement the data() and setData() methods. The setData() method is called whenever the table is edited with the QModelIndex of the cell that was modified. Use this index to retrieve the row number that was modified, and push it into a QSet. In the data() method, each time it is called with Qt::BackgroundRole or Qt::ForegroundRole, look up the row number in the set. If it is found, then return a QBrush with the "modified" color, otherwise return nothing and the default brush will be used.

When the modified rows have been committed to the database, clear the set.

Instead of deriving from QSqlTableModel, you could also use a QIdentityProxyModel and keep the QSet there. You will still have to implement data() and setData() as I described above. This is more flexible because you can use the SQL model without the proxy when you don't want row coloring, and use it with the proxy in other places. Or use a different proxy for other purposes.

franco.amato
20th March 2022, 02:42
Hi,
but I need to distinguish edited rows from new rows.
Edited rows => color 1
New rows => color 2
Unchanged rows => default color

d_stranz
20th March 2022, 15:52
Then you need to look into handling the QAbstractItemModel signals that give notification of changes in the model - dataChanged(), rowsInserted(), layoutChanged(), etc.

It sounds like you are using your table view to drive your model - that is, things get modified in the table view and then get pushed to the model rather than the other way around. If that's the case, then you are going to have to do a lot of the bookkeeping about what has changed yourself, because the model will not know until you have committed the changes. This approach is sort of backwards, I think. Usually the model is what gets updated, and it then tells the views what has changed using the signals described above.