Reputation: 59
I'm trying to improve my UI to interlink two combo boxes with each other.
My xml file contains:
<DBInfo>
<Info Org_Id="4" Database="ORACLE~orcl206~sample~2B3F1084DC06~~" />
<Info Org_Id="5" Database="ORACLE~sample1~sample1~20E786F40DF7~~" />
</DBInfo>
I'm reading data from the xml file and placing all org_Id
(4, 5) in one QStringList orgidlst
and placing all database usernames (sample, sample1) in another QStringList dbnamelst
. I'm adding items to two QComboBoxes
with these string lists:
orgidcombobox.additems(orgidlst);
DBNamecombobox.additems(dbnamelst);
Up to now working fine, but now if I want to change the item name in DBNamecombobox
to sample1
, then orgidcombobox
shall be 5
, if I change orgidcombobox
to 4
, then DBNamecombobox
shall change to sample
viceversa.
Upvotes: 0
Views: 321
Reputation: 11575
Comment from ni1ight is a good solution (I'm copying it at the end for completeness). On the other hand, if your combo boxes are sorted, then you must use something more complex. I find useful using the item data for storing DB keys and then use that to find any element, even if indices don't match anymore:
for (int ii = 0; ii < orgidlst.count(); ++ii) {
comboBox1->addItem(orgidlst[ii], orgidlst[ii]);
comboBox2->addItem(dbnamelst[ii], orgidlst[ii]);
}
connect(comboBox1, SIGNAL(currentIndexChanged(int)), SLOT(onComboIndexChanged(int)));
connect(comboBox2, SIGNAL(currentIndexChanged(int)), SLOT(onComboIndexChanged(int)));
The common slot may look like the code below, the magic resides in the QComboBox::findData
method:
void YourClass::onComboIndexChanged(int) {
// Find the current and the other combo
auto the_combo = qobject_cast<QComboBox*>(sender());
if (combo1 == nullptr) return;
auto the_other_combo = the_combo == comboBox1 ? comboBox2 : comboBox1;
const int the_other_index = the_combo->findData(the_combo->currentData());
the_other_combo->setCurrentIndex(the_other_index);
}
ni1ight solution
Works if both combo boxes preserve the elements ordering:
connect(comboBox1, SIGNAL(currentIndexChanged(int)), comboBox2, SLOT(setCurrentIndex(int)));
connect(comboBox2, SIGNAL(currentIndexChanged(int)), comboBox1, SLOT(setCurrentIndex(int)));
Upvotes: 1