PDA

View Full Version : Model/View problem in move from 4.2.3 to 4.3.0



jml
30th October 2007, 23:10
I'm having a problem with code that worked in 4.2.3 not working in 4.3.0. I've pared it down to a simple test case.

The model inherits QAbstractTableModel. relevant code:



Qt::ItemFlags TestModel::flags(const QModelIndex &index) const
{
if (index.row() == column1_.count() && index.column() != 0)
return QAbstractTableModel::flags(index);
else
return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
}

int TestModel::rowCount(const QModelIndex&) const
{
return column1_.count() + 1;
}
QVariant TestModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || role != Qt::DisplayRole)
return QVariant();
else if (index.row() == column1_.size())
return QVariant();
else if (index.column() == 0)
return column1_.at(index.row());
else
return column2_.at(index.row());
}

bool TestModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid() || role != Qt::EditRole)
return false;
if (index.row() == column1_.size())
{
if (index.column() != 0)
return false;
else
{
column1_ << value.toString();
column2_ << QString();
emit layoutChanged();
return true;
}
}
else
{
if (index.column() == 0)
column1_[index.row()] = value.toString();
else
column2_[index.row()] = value.toString();

emit dataChanged(index, index);
return true;
}
}


I'm using QTableView for the view.

In 4.2.3, when I enter data in the last row in column 1, a new row immediately appears immediately below the last row (see rowCount function). In 4.3.0, no new row appears, event though I'm emitting layoutChanged(). Is there something I'm missing and 4.2.3 let me get by?

Any help would be very much appreciated. :)

jacek
30th October 2007, 23:34
It shouldn't work with 4.2.3 either, because you don't invoke beginInsertRows() / endInsertRows() when you add a new row.

It should be:
else
{
beginInsertRows( QModelIndex(), index.row(), index.row() );
column1_ << value.toString();
column2_ << QString();
endInsertRows();
return true;
}

jml
31st October 2007, 01:07
Thanks! That seems to do the trick. The documentation seems to say to call beginInsertRows() before insertRows() (plural) - not for a single row. Since it worked with Qt 4.2, I assumed that interpretation was correct.

wysota
31st October 2007, 01:20
insertRow() calls insertRows() to do its job and insertRows() should call beginInsertRows() hence when inserting a single row (using insertRow()) beginInsertRows() is also called.

See the documentation of beginInsertRows() for more details.