Reputation: 150
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);
Upvotes: 2
Views: 3274
Reputation: 1590
You can use the currentIndexChanged
signal
One option is to use labmda.
connect(memData->comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
[=](int index)
{
// get mac address
auto oMacAddress = memData->comboBox->itemData(index, Qt::UserRole +1);
});
Or add slot to your class
connect(memData->comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MyClass::HandleIndexChanged);
void MyClass::HandleIndexChanged(int index)
{
// get mac address
auto oMacAddress = memData->comboBox->itemData(index, Qt::UserRole +1);
}
Upvotes: 1
Reputation: 244122
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);
Upvotes: 3