[SOLVED] How to initialize a bunch of similar comboBoxes at once in a loop?

  • Hi,

    I am wondering if there is a simple way to initialize combo boxes which are all of the same content at once in a loop using:

    @ui->ComboBoxXYZ->addItem("somedescription", someinteger);@


    The combo boxes in each line simlpy should contain the same entries.

    I am an absolute qt-newbie and would appreciate any hint on this.

    Thanks in advance



  • Hi,

    if you use a nameing schema for your combo boxes, you can use findChildren with QRegularExpression to achieve your result.

    For example in my ui are defined several QComboBox named "comboBox_1", "comboBox_2" and so on.
    This code
    Widget::Widget(QWidget *parent) :
    ui(new Ui::Widget)

    QList<QComboBox*> combos = findChildren<QComboBox*>( QRegular[removed] "comboBox_.*"));
    QStringList comboItems;
    comboItems << "Foo" << "Bar";

    Q_FOREACH (QComboBox* combo, combos) {
    add "Foo" and "Bar" to all of them

    P.S. I don't know why the string QRegularExpression is shown as QRegular[removed]

  • You can also consider using a layout such as "QGridLayout":http://qt-project.org/doc/qt-5.0/qtwidgets/qgridlayout.html and to add the combo boxes using method "addWidget":http://qt-project.org/doc/qt-5.0/qtwidgets/qgridlayout.html#addWidget

  • mcosta,

    thank you for your suggestion. It is a very nice solution. I just had to change some little things to deal with the item data. I also changed it to work with QT4.

    This is my code now:

    @//Fill comboboxes for area and formats with data

      QList<QComboBox*> comboBoxesArea = findChildren<QComboBox*>(QRegExp("comboBoxArea_.*"));
      QList<QComboBox*> comboBoxesFormat = findChildren<QComboBox*>(QRegExp("comboBoxFormat_.*"));
      QStringList comboItemsArea;
      QStringList comboItemsFormat;
      QList<int> comboValuesArea;
      QList<int> comboValuesFormat;
      comboItemsArea << " " << "E" << "A" << "M" << "DB" << "Z" << "T" << "IEC_Z" << "IEC_T";
      comboItemsFormat << " " << "BOOL" << "BYTE" << "WORD" << "DWORD" << "INT" << "DINT" << "REAL";
      comboValuesArea << 0x0 << daveInputs << daveOutputs << daveFlags << daveDB << daveCounter << daveTimer << daveCounter200 << daveTimer200;
      comboValuesFormat << 0x0 << AnzFormatBool << AnzFormatHexadezimal << AnzFormatHexadezimal << AnzFormatHexadezimal << AnzFormatDezimal << AnzFormatDezimal << AnzFormatGleitpunkt;
      int areaItemsCount = 0;
      int formatItemsCount = 0;
      Q_FOREACH(QComboBox* areaBox,comboBoxesArea)
      Q_FOREACH (QComboBox* formatBox,comboBoxesFormat) {

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.