0

I have a QHash of items I want to display in a QTableView. So I need a model. The MyClass has an internal id, which is used to insert into the map. Something like this:

// when adding a new item
my_super_hash[item->id] = item;

When implementing the model I found that all the methods in the model talk about the "index" which was clicked (or whatever...).

Can anyone remomend me how to map between the QHash and the model? (QHash which is key based, and the model is index based).


Option 1 - not ideal

One option is to create at startup a list which maps between the index to the key:

int i = 0;
foreach( MyClass* c, my_super_hash )
  conversion[i] = c->id

Now inside the models re-implementation methods, I use

int key = conversion[index.row()];
MyClass * value = my_super_hash[key];

This idea seems messy, and I want a better implementation.

elcuco
  • 8,948
  • 9
  • 47
  • 69

2 Answers2

0

By the way what kind of hash do you have: e.g. if QHash<int, QVariant> you could use the key part as an "index" in the model.

Neox
  • 2,000
  • 13
  • 12
  • I probably do not understand what do you ask, or I fail to undestand something about the MVC implementation in Qt4: the QModelIndex I get specific which column/row has been clicked (or been painted). I cannot user that number as the key value, because ID might start from 1000, and the model may contain only 10 values (1000, 1243, 7772, 9811234). – elcuco Jan 05 '12 at 08:44
  • 1
    Sorry I was assuming that the keys in the hash will be ordered like 1 through 20 so you could use them as indexes. But I see that is not the case. Well than in my opinion your implementation is though messy but unavoidable. In my practice I usually use QMaps if keys in my data cannot be used as indexes. – Neox Jan 05 '12 at 08:57
  • Add a new answer, saying "use QMap instead of QHash" and you get more reputation and this question will get a green mark. – elcuco Jan 05 '12 at 09:24
0

Using QMap instead of QHash seems more reasonable, as Neox recommended on his comment.

EDIT:

OK, after implementation I found problems: Lets say I have IDs 100,102,103,105 (101, 104 are not available), my model will have "holes" in it.

What happens is that the model has 4 items, and when I ask for item number #2, QMap::at(1) will return NULL. It seems in practice, 102 will be at #3. Arg... :(

EDIT 2:

I tried this code:

#if 0
return my_super_map.at(index);
#else
int i = 0;
foreach (MyClass *c, my_super_map) {
    if (i == index)
        return c;
    i++;
}
return NULL;
#endif

While this does work, it's damn slow. I might need to make another translation table, as in the original response. (this is called inside the data() method for example, I thought the values where cached inside the view, but I was wrong).

elcuco
  • 8,948
  • 9
  • 47
  • 69