[Interest] Proper way of updating a model?
André Somers
andre at familiesomers.nl
Thu Aug 23 11:04:01 CEST 2012
Op 22-8-2012 20:29, Stephen Chu schreef:
> Now I have a question on how to properly update the model. My model is a
> read-only representation of a database. I am using a QTreeView to hold
> the model. The data themselves are not tree-like but I like the visual
> of QTreeView better.
So, you *do* have a table model, but you are just displaying it in a
QTreeView? That's very possible, of course. Note that QTableView can be
given the same appearance as QTreeView, but is more efficient at
layouting because it does not need to deal with the (complex) tree
aspects of it.
Please keep in mind that *any* model can in principle be viewed in *any*
view. You may loose certain aspects of the data of not use all features
of the view, but normally, it will work. That's because views only rely
on the common interface provided by QAbstractItemModel.
> The model needs to update itself periodically from the remote database.
> I keep a QList of data IDs and rebuild the list every time I get a new
> snapshot from the database.
For efficient updating, you will need to keep track of changes: inserts,
deletes and updates of items. Just rebuilding will generally not be very
efficient.
>
> What's the recommended way to reflect the changes to the view? I need to
> keep the current selection and scroll position of the QTreeView between
> updates.
>
> Do I reset the model? Or do I remove deleted rows and insert new ones?
No, resetting is not the way. It will result in loosing selection,
scroll position and is generally visually disturbing for the user. As
others have notices, the beginInsertRows, beginRemoveRows and their
respective end* functions are your tools, together with emitting the
dataChanged signal for updates to data.
However, it also depends on the size of your dataset. Are you talking 10
rows, 1k, 1M or even more?
André
More information about the Interest
mailing list