Search code examples
c++qtqt5qcombobox

Using Qt::UserRole and Qt::DisplayRole for Items in QComboBox


I am new to C++ Qt. I am trying to populate a QComboBox with values different than the values that need to be used. For example, QComboBox shows name of devices but on selection sends the mac address of that device. I have the data.

I tried using Qt::UserRole and Qt::DisplayRole but only the values mentioned in DisplayRole are used. I think I need to define the roles? If yes, then how? Any help regarding this?

QStandardItemModel *model = new QStandardItemModel(this);
int i = 0;
for (auto info : list)
{
    if (info.validateMACAddress())
    {
        memData->comboBox->addItem(info.getMacAddress().arg(i));
        memData->comboBox->setItemData(i, info.getDeviceName(), Qt::DisplayRole);
        memData->comboBox->setItemData(i, info.getMacAddress(), Qt::UserRole + 1);
        i++;
    }
}
memData->comboBox->setModel(model);

Solution

  • It is not necessary to establish a model since QComboBox has an internal model. Also memData->comboBox->setItemData (i, text, Qt::DisplayRole); is equivalent to memData->comboBox->addItem(text); so just place one of them.

    int i = 0;
    for (auto info : list){
        if (info.validateMACAddress()){
            memData->comboBox->addItem(info.getMacAddress().arg(i));
            memData->comboBox->setItemData(i, info.getMacAddress(), Qt::UserRole + 1);
            i++;
        }
    }
    

    And to get the mac you should use the currentData() method in the slot:

    // Slot:
    
    auto mac = memData->comboBox->currentData(Qt::UserRole + 1);