Search code examples
qmlqtquick2datamodelqabstracttablemodelqabstractlistmodel

Why using QAbstractTableModel instead of QAbstractListModel?


I've implemented TableView in QML using TableViewColumns with some roles like this:

TableView {
    TableViewColumn {
        role: "role1"
        title: "Role1"
    }
    ...
}

It's bound to a C++ model, inherited from QAbstractListModel with all the roles defined and I find it perfectly natural.

However, I've found out that there also exists QAbstractTableModel, which allows using column indices. I've understood that I should've probably used it, but I prefer roles to column indices.

Could someone please explain what is the advantage of using QAbstractTableModel?


Solution

  • There isn't one unless your using Qt Widgets vs. Qt Quick.

    Qt in general has a Model/View architecture and this architecture can be used either with Qt Widgets or Qt Quick. Its the same concept in both but the View classes are different between the two especially the table views.

    In Qt Widgets you have QTableView, this view expects the model data to be layed out in a table (i.e. rows and columns) and as such one would use a sub-class of the QAbstractTableModel to provide it this data.

    In Qt Quick however the TableView type is NOT a one-to-one copy of the QTableView class. In fact its completely different and it expects the data in any model provided to it to be laied out in a list (i.e. rows but only 1 column) NOT a table. To achive a table like arragement of data the TableView type uses roles in lue of columns.

    So in Qt Widgets one can use the QTableView class and use a sub-class of QAbstractTableModel to provide it data in a table layout (rows and columns) but in Qt Quick one uses the TableView type and uses a sub-class of QAbstractListModel to provide it data in a list layout (rows and only 1 column) but instead of showing only the Qt::DisplayRole in each cell one can declare a different role to be used in each column of the TableView.

    Its not so much as one had more value over the other its just that one View type/class expects the data in a different format then the other.

    If your sitting there thinking Qt has made this needlessly complicated just know that the table view is the odd duck; if you were talking about a list view the QListView (Qt Widgets) class and the ListView (Qt Quick) type are actually nearly a one-to-one in behaviour, they can both use the same model interchangabley. That is you can put your model in a shared library and use it in either a Qt Quick or Qt Widgets application with no modifications. It should be noted that the same can be achived for QTableView/TableView but the model will have to support both expectations, showing the data as both a table with rows and columns and as a list with rows and roles.

    I hope that anwsers your question.

    Until next time think imaginatively and design creatively