Finding Referenced Object for Alphabetically Sorted QComboBox with Duplicates
-
I am trying to subclass QComboBox to create an alphabetically sorted text-based combo box for a bunch of objects of the same class. In order to match the selection of the combo box and my objects, I keep track of the match between the indexes and objects using a QMap. The question I have originates from the wish to order the items alphabetically. Unfortunately, the QComboBox::addItem does not return the index at which the item was added. That is, the documentation says that items are appended (so will have the largest index). However: what is the index of added items or selected item when alphabetically sorted? Does the sorting re-assign indexes or not? Does anybody have experience with this?
-
Can't you use duplicatesEnabled
-
I may have found a solution based on currentIndex, which is only changed when adding or removing items. It seems not to change by selection according to the documentation. This was my confusion... and with the activated(int) signal I should be able to find the object by its index. Can anybody confirm this?
-
For something like this I would store some sort of id number with each item and not rely on the index value from the control. This is done with setItemData(), itemData(), and the second parameter of addItem() or the third parameter of insertItem().
The data could be anything. It could be your own index value for example. I sometimes cast an enum value to this parameter. A simple change like sorting won't break your program if you go this route.
The signal activated(int) appears to be identical to currentIndexChanged(int) except it is always triggered even if the user doesn't select a different item in the combo box. Using this signal means your program will have to respond needlessly even if the current item hasn't been changed. I can't picture how this would help for a sorted combo box.
-
Ok, I have seen the "Data" aspect but didn't really get it. As fas as I understand the Data must be of type QVariant. Ideally, I would however want to store a pointer to an object of a class that I defined myself. How could I do so, i.e., both for storing the pointer and retrieving it as pointer to the original object?
-
Hi,
What type is your class made of ?
-
So declare the pointer to your class as meta type with Q_DECLARE_METATYPE, then you can use QVariant::setValue and QVariant::value to load and store the pointer to your object.