PDA

View Full Version : Effective way to parse through a model intended to store key and associated values.



schall_l
3rd June 2009, 16:22
I have a model, deriving from QStandardItemModel, that is used to represent keys with associated values. The key is stored in the first column of each row, while the associated values are stored in the following columns from each row.

I have quite often to verify if a certain key is already stored in the model, if this is the case I am leaving the model untouched otherwhise I am adding a new row.

So each time I have to verify if a certain key is already stored in the model, I am parsing the entire model like this:



// frame_id contains the key we may want to store in the model

// Get the amount of rows already stored in the model
int rowCount = m_model->rowCount(QModelIndex());
int row;

unsigned int stored_id;
// Parse the model to look if this identifier is already stored
for (row = 0; row < rowCount; row++) {
stored_id = m_model->data(m_model->index(row,0,QModelIndex()),Qt::DisplayRole).toUInt ();
if (stored_id == frame_id) {
// This identifier is already stored in the model, so we simply return it color
return QColor(m_model->data(m_model->index(row,1,QModelIndex()),Qt::DisplayRole).toStri ng());
}
}

// This identifier is not already stored in the model, so we will add it at the end.
m_model->insertRows(row,1,QModelIndex());
m_model->setData(m_model->index(row,0,QModelIndex()),frame.id);
m_model->setData(m_model->index(row,1,QModelIndex()),QColor(Qt::white).name( ));
m_model->setData(m_model->index(row,2,QModelIndex()),"");

I am wondering if parsing the entire model is the correct way to do or if there is an other type of model I could use in order to make this more efficient.

Thanks.

wysota
3rd June 2009, 20:08
Such model is very inefficient because you can only iterate it as a sequence. You could store the data in a QHash and reimplement QAbstractItemModel::match() or provide your own method for searching. Alternatively if keys are unique, store them in a private QSet object and provide a contains() method for your model.

Also, if you can make sure your keys are always sorted, you can use binary search to find the key quickly in the standard model.

So you see there are many ways to solve your problem - pick one that suits you best.