PDA

View Full Version : Is it possible to share a model between multiple views but display different records?



stevebakh
22nd March 2010, 22:06
I feel like this place is my lifeline the past couple of weeks!

Does anybody know if it's possible to have a single model shared by multiple views, but, showing different subsets of data?

My scenario:
I have a model that represents a database table QSqlTableModel or QSqlRelationalTableModel and I have multiple views on a single screen. I wish to display, for example, all records created before date X in one view and all records created after date X in another view.

The only examples I've found so far that allow the sharing of models between multiple views seem to keep the same records displayed in each view, rather than displaying different subsets of data.

Is this possible, or will I need to instantiate multiple models? I'm trying to fiddle with QSortFilterProxyModel now, but I don't think it's entirely suitable for what I want here.

Thanks!

ChrisW67
22nd March 2010, 23:54
Yes. QSortFilterProxyModel (or another QAbstractProxyModel derivative) is designed precisely for this. Ingredients:

One base QSqlTableModel instance. Data is stored once in memory.
One QSortFilterProxyModel derivative for each view. Override filterAcceptsRow() as required to select the rows you want, and lessThan() if you want to sort them in some special way. Set the sourceModel() to your base model. You could get away with the one proxy class with an "Invert filter" option: there'd still be two instances.
Two views. Set the model to an instance of the relevant QSortFilterProxyModel derivative.

Links to the relevant tutorials are in the QSortFilterProxyModel page.

stevebakh
25th March 2010, 14:20
Thanks a lot for the tip. I'm in the process of implementing it now and it seems this is what I needed afterall!