Home > Net >  Configuring multiple QComboBoxes
Configuring multiple QComboBoxes

Time:09-01

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 to add items to each combo box 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));

What is the easiest method to do the same settings to other combo boxes by using for loop?

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 addItems 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));
    }
}
  •  Tags:  
  • qt
  • Related