Search code examples
qtinheritanceqmlabstract-class

What's the purpose of inheriting QAbstractTableModel, QAbstractListModel, etc. for ListView, GridView and TableView


I could have a simple QVector, QList, etc. of QObject to present in ListView, GridView and TableView and add/edit/remove items in/from those View. To me using QVector, QList, etc. of QObject* is the easiest way to accomplish the ultimate goal. What's the real benefit of inheriting QAbstractTableModel, QAbstractListModel, etc.? In WPF we've VirtualizingStackPanel and some properties to boost performance in such type of View. Does inheriting those Abstract..Model serve the same purpose or either way (inheriting or using plain QVector/QList), performance will be same?


Solution

  • The advantages of QAbstractItemModel and subclasses are mainly increased performance when handling larger lists, and increased flexibility by using proxy models:

    1. Partial updates: A model can tell the view that single rows or ranges of rows were inserted, moved, removed or updated which then the view can act upon in a smarter way than throwing away and rebuilding everything. The cost of inserting an item in the middle of 10k other items is cheap, for example.

    2. Lower overhead: A large list of, say, 50k QObject*s would have a major overhead, both in cost for the objects themselves and in handling all the signal/slot connections for handling the property updates.

    3. A model can act as an adapter to an already existing data structure, without the need to hold all the data in the model (although that can be tricky in practice, to guarantee correctness/consistency)

    4. Lazy-loading: The model can load data on demand as the user is navigating the view, without having to have all data already available (see fetchMore()/canFetchMore()).

    5. Flexibility through proxies: QAbstractProxyModel and subclasses (in particular, QSortFilterProxyModel) allow stacking of models to filter/sort/modify the data in the original model. With QSortFilterProxyModel sorting and filtering is usually much simpler to implement (and without changing the original data/model) than implementing it manually for a QList. Simple modifications like changing the returned data for a certain role can be implemented by subclassing QIdentityProxyModel.

    6. More complex data structures: QAbstractItemModel also allows for trees (tricky to implement though) and tables. These are more often used in "traditional" (QWidget-based) desktop UIs than in embedded/mobile touch UIs though.