Search code examples
qtqlist

How to make a list of children widgets on a layout in QT?


A nice simple example would be nice. For my part, I wish to do something like this:

myLayout->addWidget(myButton1);
myLayout->addWidget(myButton2);

myButtonList<QToolButtons*>->append(myLayout->findChildren(QToolButtons));

myButtonList->at(1)->setText("This is 'myButton2'");

Solution

  • Use QList along with using findChildren with QWidget because QLayout does not show QWidgets as its children and a QWidget have a parent QWidget only. Refer this

    QWidget w;
    QPushButton *p1= new QPushButton;
    QPushButton *p2= new QPushButton;
    QHBoxLayout l;
    l.addWidget(p1);
    l.addWidget(p2);
    w.setLayout(&l);
    QList<QPushButton*> buttons = w.findChildren<QPushButton*>();
    buttons.at(0)->setText("Hello I am P1"); 
    buttons.at(1)->setText("Hello I am P2");
    w.show();