0
votes

I have an abstractTable model with a very odd problem.

The rowCount method;

int ordersModel::rowCount(const QModelIndex &) const
{
    int i = oData->count();
    qDebug() << "rowc=" << i;

    return 711;
  //  return   oData->count();

}

Works when I hard code the value (711 or something lower) but if I use return i; or return oData->count(); the table displays nothing. (qDebug() reports that the data has 711 entries.

The headers appear correctly. I'm in Qt 5.4.1, Windows 7.

Stumped!

2
Please add more information. What is ordersModel? Have you tried to find const 711 in other files (may it is hard coded somewhere else)? - Ilya
Hi, I think that you're looking at the problem from the wrong angle: the rowCount() method will be called by the any view at not predictable times: are you sure that the oData object or structure is properly initialized, when the method is called. Is the output you're sending to qDebug() stable? By just looking at the few lines of code you posted it's a bit difficult to help you. - Albert
Does oData have any items when you assign it to the item view? If you add items after assigning it to the view, you must run the beginInsertRows and endInsertRows functions to force the view to recheck the data. - RobbieE
Albert set me on the right track. I still don't understand why the sequence failed, but the record count was wrong when the update started despite what rowCount returned. By adding beginResetModel and endResetModel around the data load, the table views update correctly. Many thanks Albert and Robbie (your suggestion sent me to the docs). - john elemans

2 Answers

1
votes

Try

int MyModel::rowCount(const QModelIndex &parent) const {

  if ( parent.isValid() )
      return 0;

  return m_entryList.size();
}
0
votes

Your problem may have nothing to do with the rowCount method itself, although even that method is not correct - see the other answer. Other aspects of the model's implementation likely don't fulfill the basic contract that every model must fulfill.

The following sequence of events takes place:

  1. Your model starts with no elements.
  2. A view is attached to the model. The view expects the model to fulfill the requirements of a QAbstractItemModel.
  3. You add data to the model. The model fails to emit the rowsInserted signal - it doesn't call beginInsertRows and endInsertRows. It has broken its contract.
  4. You've now triggered undefined behavior in the view and Things Don't Work™.

See the first section of this answer about model semantics, and make sure you understand it and follow the requirements.