Should QAbstractItemModel :: index (row, column, parent) check for invalid inputs?

Subclassing QAbstractItemModel, I applied my own index () method as needed. I am currently checking valid data, but I am wondering if this is correct. I am wondering if this is really for creating an index for a non-existent piece of data? Perhaps when inserting a row or column?

code:

QModelIndex LicenseDataModel::index(int row, int column, const QModelIndex & /*parent*/) const
{
    /// TODO: Is this necessary? Should we avoid creating invalid indexes? Or could this
    /// be a bug?
    if (validRowColumn(row, column))
        return createIndex(row, column);
    return QModelIndex();
}
+4
source share
1 answer

[If anyone has a better answer, I will gladly agree with him. ]

Looking at the source of QListWidget , it seems that checking the inputs is what Qt does itself:

QModelIndex QListModel::index(int row, int column, const QModelIndex &parent) const
{
    if (hasIndex(row, column, parent))
        return createIndex(row, column, items.at(row));
    return QModelIndex();
}

, hasIndex(), , validRowColumn().

bool QAbstractItemModel::hasIndex(int row, int column, const QModelIndex &parent) const
{
    if (row < 0 || column < 0)
        return false;
    return row < rowCount(parent) && column < columnCount(parent);
}

, index.isValid() , hasIndex(index.row(), index.column(), index.parent()) . , , hasIndex(QModelIndex &). hasIndex() , QModelIndex::isValid() :

inline bool isValid() const { return (r >= 0) && (c >= 0) && (m != 0); }
+4

All Articles