I have a basic question. I have combo boxes with name comboBox_frequency_1
, comboBox_frequency_2
,comboBox_frequency_3
,comboBox_frequency_4
, comboBox_frequency_5
etc.
I need add items to each combo boxes as below:
ui->comboBox_frequency_1->addItem("10Hz", QVariant(100));
ui->comboBox_frequency_1->addItem("15Hz", QVariant(150));
ui->comboBox_frequency_1->addItem("20Hz", QVariant(200));
ui->comboBox_frequency_1->addItem("25Hz", QVariant(250));
ui->comboBox_frequency_1->addItem("30Hz", QVariant(300));
How can I do the same settings to other combo boxes, I assume there should be for
loop to do that but don't know how exactly to execute it. Can some one help me please?
CodePudding user response:
You can create an array of those UI elements and iterate over that like so:
QComboBox* boxes[] { ui->comboBox_frequency_1, ui->comboBox_frequency_2, ui->comboBox_frequency_3, ui->comboBox_frequency_4, ui->comboBox_frequency_5 };
for(auto* cb : boxes)
{
cb->addItem("10Hz", QVariant(100));
cb->addItem("15Hz", QVariant(150));
cb->addItem("20Hz", QVariant(200));
cb->addItem("25Hz", QVariant(250));
cb->addItem("30Hz", QVariant(300));
}
You may want to create those QComboBoxes in code instead of the UI file if you have such a long list of them, so you can store them in an array at creation and don't have to name them individually.
Also, it's possible to replace the block of addItem
s with a loop and a table. That may or may not be more readable depending on size of the table.
QComboBox* boxes[] { ui->comboBox_frequency_1, ui->comboBox_frequency_2, ui->comboBox_frequency_3, ui->comboBox_frequency_4, ui->comboBox_frequency_5 };
const int values[] { 10, 15, 20, 25, 30 };
for(auto* cb : boxes)
{
for(auto val : values)
{
cb->addItem(QString::number(val) "Hz", QVariant(val*10));
}
}