I added 10 checkboxes to the window in designer mode. These are checkbox1,checkbox2,...,checkbox10 objects that are not an array. How can I check the status of each checkbox in a loop?

  • one
    If refactoring using an array is totally unacceptable - use an array of addresses, stick checkbox addresses into it and work in a loop with this array of addresses ... - Harry
  • The problem is that in the designer mode, I cannot put these checkboxes in an array, and the prospect of rewriting the entire window through the creation of a code depresses me. - Andrey Solodovnikov
  • one
    Look at this question, here is a similar situation. Stackoverflow.com/questions/590962/… - Bearded Beaver
  • Oh, thanks, this option suits me as a whole, although I’ve still found such a thing as a QButtonGroup, it seems right for that and created. - Andrey Solodovnikov

2 answers 2

To bypass all the child objects of a particular type, you can use QObject::findWidget . Example:

 for (auto child: parentWidget.findChildren<QCheckBox*>()) { // Работаем с child как QCheckBox* if (child->isChecked()) ... } 

    If you absolutely do not want to create a form procedurally, then you can iterate over the child elements. Method

     QObjectList &QObject::children() 

    to help you. QObjectList is declared in Qt like this

     typedef QList<QObject*> QObjectList; 

    Next, we iterate over the elements in search of elements with the desired name (then we execute the code inside the window class after initializing ui). If the desired object is found, then convert it to QCheckBox using qobject_cast. You can immediately put pointers to them in a QList or QMap.

     QObjectList childs = this->children(); QMap<QString, QCheckBox*> boxMap; QList<QCheckBox*> boxList; QList<QObject*>::iterator i; for (i = list.begin(); i != list.end(); ++i){ if (i->objectName().left(8) == "checkbox"){ QCheckBox *box = qobject_cast<QCheckBox *>(i); if (box){ boxMap[box->objectName()] = box; boxList.append(box); } } } 

    You can also use findChild to get pointers to child elements by name and class, or findChildren to search for child elements by even a string at least RegExp.

    • one
      Why these crutches if you can use findChildren right findChildren ? - αλεχολυτ
    • For example, to bypass all child objects or to search among them for several conditions — one pass instead of several searches will be more efficient. Also, the search terms can be any are set by code, not by string or RegExp. In your case, it will be more efficient to findChildren by RegExp. - Vitto74
    • I mean, it follows from the solvable problem. If off-the-shelf functions solve a problem, then handwritten solutions should be avoided. If the flexibility of library options is not enough, then, of course, you have to bike. - αλεχολυτ