C. Binair
C. Binair

Reputation: 451

QCombobox with additional data for items next to the string

I'm having a database with two types of one thing. Let's say I have animals and then the two types are birds and fish. I want one combobox in which the two are combined. So basically you can chose any animal either some bird or some fish.

In the combobox I would like to display the names of all the animals in the database, but I would also like to add some extra data to each item next to the name to use that for programming. I would like to add the index and the type.

Before I've used the userdata variable to add the index, but then I only had one type so knew which db it should query after. (See QCombobox documentation: addItem(const QString &text, const QVariant &userData = QVariant())). So what I did then was:

ui.comboBox->addItem("Animal name", animal_index);

I'm not sure if this is the purpose of the userdata variable but this way it did what I wanted it to do. When an okay button was pressed I can read the current data and use that to query the database for all properties of that animal.

But what I want now is to add two additional information variables to a combobox item. Such that I know which db table I should query to obtain the animal properties.

So I would either like to be able do something like:

ui.comboBox->addItem("Animal name", animal_index, animal type);

I expect this also requires a change to the current data procedure to actually obtain the second variable. So what I think would be better is with the use of an array/vector/struct:

ui.comboBox->addItem("Animal name", [animal_index, animal type]);

But I'm not sure how to make a array/vector/struct as QVariant.

I know I could also just make ranges in the index. So all bird have a index between 0 and 999 and all fish between 1000-1999. But this would require some extra database management which I do not want.

Upvotes: 2

Views: 3325

Answers (1)

vahancho
vahancho

Reputation: 21240

You can construct a variant out of a QList and set it as a user data. For example:

ui.comboBox->addItem("Animal name",
                     QList<QVariant>() << animal_index << animal_type);

To read the item data back you can do this:

auto data = ui.comboBox->itemData(0).value<QList<QVariant>>();
assert(data.size() == 2);
auto animal_index = data.first().toInt();
auto animal_type = data.last().toInt();

Upvotes: 4

Related Questions