4

Trying to understand QAbstractTableModel more, I came across the virtual methods of rowCount and columnCount which need to be implemented when subclassing QAbstractTableModel.

Take int QAbstractItemModel::columnCount(const QModelIndex &parent = QModelIndex()) const for example, the Qt official documentation says "In most subclasses, the number of columns is independent of the parent."; and gives the following code snippet:

int DomModel::columnCount(const QModelIndex &parent) const
{
    return 3;
}

The above-mentioned is straight-forward to understand, which, nonetheless, makes me wonder when the column number will NOT be independent of the param "parent"? I simply cannot come up with a scenario where the column number of a table is not a fixed constant, but a variable depending on the index of a particular cell.

It just doesn't seem like this param is needed at all, can someone share an example where the index param is actually useful?

JackOuttaBox
  • 345
  • 5
  • 12
  • 4
    It's relevant to hierarchical views only - for instance tree views. Table items have no parent at all. In tree views the number of columns for different items can be different, depending on their place in the hierarchy. – vahancho Feb 18 '19 at 12:46
  • @vahancho Got it, thanks! – JackOuttaBox Feb 18 '19 at 13:08

1 Answers1

3

The parent parameter is useful when you have a hierarchy, because your data depends on where it is located in the hierarchy, and so can depend the row or column count.

enter image description here

From this picture from the doc, you can imagine that the column-count could be different for the row containing A than the sub elements like the row containing B.

You can read more in the doc : https://doc.qt.io/qt-5/model-view-programming.html#model-classes

ymoreau
  • 3,402
  • 1
  • 22
  • 60