QStandardItemModel and QSortFilterProxyModel: maintaining correspondence between indexes and items (and underlying data)
-
I have big problems using Qt model/view architecture. Looks like I'm misunderstanding something.
I have a vector of data that I want to visualize with QTreeView. I use QStandardModel, like this:
@void fillFromList(const std::vector<CFileSystemObject> &items)
{
_model->clear(); // QStandardItemModel
_model->setColumnCount(NumberOfColumns);for (int i = 0; i < (int)items.size(); ++i)
{
QStandardItem * fileNameItem = new QStandardItem();
fileNameItem->setData(items[i].name(), Qt::DisplayRole);
fileNameItem->setData(items[i].hash(), Qt::UserRole); // Unique identifier for this object;
_model->setItem(i, NameColumn, fileNameItem);//... and so on for all other columns ...
}
}@Then, on top of this, I have a model inherited from QSortFilterProxyModel with overriden lessThan for custom sorting. But I have problems getting original model's items from indexes:
@bool CSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
assert(left.column() == right.column());
assert(left.isValid() && right.isValid());
const int sortColumn = left.column();QStandardItemModel * srcModel = dynamic_cast<QStandardItemModel*>(sourceModel()); // Ugly!
QStandardItem * l = srcModel->item(left.row(), left.column()); // Is sometimes null!
QStandardItem * r = srcModel->item(right.row(), right.column()); // Has been OK so farif (!l || !r)
return true;
// Actual sorting done below...
}@Is there a mistake in my code? Why can srcModel->item yield null for one of the items passed to lessThan? The idea here is to retirive the original QStandardItem, then hash from its data(Qt::UserRole) and then the actual underlying data from the array that's being visualized. Is the general design OK? Any improvement suggestions? But mainly I'm looking to fix the severe bugs at this point.