Qt6 topics merged with General

QComboBox for Equally named Items

  • I have a collection of named items. It is allowed to have multiple items with the same name. I need a QComboBox feature to select an item from the set, which I currently setup by using the names of the items as text values for the selection options. How can I create a QComboBox that may contain multiple times the same value of displayed text for the selection option, while still being able to find the reference back to the appropriate item? Is there some variant of a QComboBox that works with something like a QComboBoxItem?

    By the way, I use alphabetic ordering...

  • Qt Champions 2017

    Atleast I'm not very clear about the question. Are you asking something like follows ?

    QStringList list;
    list << "A" << "A" << "B" <<"B";
    QComboBox box;


  • Lifetime Qt Champion

    Hi @ModelTech,

    you can add a const QVariant &userData to each item when adding: http://doc.qt.io/qt-5/qcombobox.html#addItem and later get back with http://doc.qt.io/qt-5/qcombobox.html#itemData for a specific index.

    Does that help you?

  • Thanks for the answers!

    @aha_1980 If the const QVariant &userData can be a pointer to my item (which is subclassed from QObject and uses the Q_OBJECT macro), than this solves what I am looking for. In the QVariant documentation, I read that: "If the QVariant contains a pointer to a type derived from QObject then T may be any QObject type. If the pointer stored in the QVariant can be qobject_cast to T, then that result is returned. Otherwise a null pointer is returned. Note that this only works for QObject subclasses which use the Q_OBJECT macro." So, this is the way to go.

    Unfortunately, I have not used QVariant before. So, I have been reading more about it but could not find example code for this particular situation. Would anybody have example code for a QVariant for such a pointer? I can only imagine something like:

    MySubClassedQObjectClass *MyObject, *MyOtherObject;
    QVariant Variant = QVariant::fromValue(MyObject);
    MyOtherObject = Variant.value<MySubClassedQObjectClass*>()

  • Well, the code I came up with seems to work.

    I think however that I need to store a QMap from the MySubClassedQObjectClass items to the corresponding QVariants in order to be able to call QComboBox::fromData but that is fine. Unless there is a better way for this. Anyway, I think this is a good solution!

    The only thing that does not work anymore is the alphabetic insertion into the QComboBox that I realized using QComboBox::setInsertPolicy(QComboBox::InsertAlphabetically). Is this a bug?

Log in to reply