Question

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.

Was it helpful?

Solution 2

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).

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top