[solved] foreach (QPushButton, QVBoxLayout) question ?

  • The following code adds Pushbuttons to QVBoxLayout:
    @void MainWindow::on_pb_test_1_clicked() {

    vlw_1 = new QWidget(this);
    vlw_1->setGeometry(QRect(10, 10, 40, 200));
    vl_1 = new QVBoxLayout(vlw_1);
    vl_1->setContentsMargins(11, 11, 11, 11);
    vl_1->setContentsMargins(0, 0, 0, 0);
    for (int i=0; i<5;i++) {
        pb_x = new QPushButton(vlw_1);
    vlw_1->setStyleSheet("QPushButton:checked{color: green; background-color: red;}");


    in another function i want to access all this Pushbuttons in this QVBoxLayout using 'foreach'

    @void MainWindow::on_pb_test_2_clicked() {

    qDebug() << vl_1->count();
    qDebug() << vlw_1->children().count();
    foreach(QPushButton *x, ??? ) {
        // do something on each Pushbutton

    By what should be "???" substituted ?

  • Moderators

    Nothing: it will not work with QLayout.

    But you can use "QObject::findChildren()":http://qt-project.org/doc/qt-5/qobject.html#findChildren to get all QPushButtons and iterate over the list that is returned.

  • @void MainWindow::on_pb_test_2_clicked() {

    QList<QPushButton*> bList = vlw_1->findChildren<QPushButton*>();
    foreach(QPushButton *x, bList) 
        qDebug() << x->objectName() ;

    works nice on the QWidget vlw_1. Maybe my fist foreach approach works on QWidget ?

  • Moderators

    "foreach" works on container classes, that is:

    • QList
    • QStringList
    • QMap
    • QHash
    • QVector
    • probably some more (QQueue, QMultiHash, etc.)

    it does not work on QWidget or QLayout by itself. But when you have - for example - a list of widgets, then it is a different story (and a happy one: see the solution that works for you :)).

Log in to reply

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