[RESOLVED] What would be the best way to tie an int value to an item in a QComboBox?



  • Hi,

    What would be the best way to tie an int value to an item in a QComboBox?

    In other words what I have is about 30 items in a QComboBox and each item is tied to an int number and I was wondering if I could somehow assign this int value when adding the item to the comboBox so that whenever that item is selected the value will be the int not the string (currentText()).

    This is what I could do but I think is overkill, too many if statements...

    @
    //add items
    comboBox->addItem("Item One");
    comboBox->addItem("Item Two");@

    @
    // check what item is selected and assign int value
    if(comboBox->currentText() == "Item One")
    {
    // assign intValue for item One

    }else if(comboBox->currentText() == "Item Two")
    {
        // assign intValue for item two
        
    }...@
    

    What I would like to do instead is assign a value when adding the items to the ComboBox
    @ // add items
    comboBox->addItem("Item One", 100);
    comboBox->addItem("Item Two", 200);@

    and than somehow ask for that value...
    @ // call for intValue of the selected item
    comboBox->currentValue(); // this would output the int value
    @

    Sorry if what I'm asking doesn't make too much sense.



  • See that QComboBox::addItem has second argument named 'userData', so this:
    @comboBox->addItem("Item One", 100);@

    is perfectly valid, but then you need such thing:

    @comboBox->itemData( comboBox->currentIndex () );@



  • Got it, I tried this but I was definitely doing it wrong.

    this is what I was doing...
    @comboBox->itemData->currentIndex ();@

    Thanks a lot


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.