Important: Please read the Qt Code of Conduct -

Creating Dynamic GridLayout

  • Hi

    For the code below, I am trying to arrange unknown number of buttons (below it is 34 to try the algorithm) in a grid layout. There will be 4 columns.

    But when I run the code all the buttons are located at the same point. Isn't it supposed to be arranged in grid?

    Thanks in advance...
    [code]int main(int argc, char *argv[])
    QApplication app(argc, argv);
    QWidget *window = new QWidget;
    QGridLayout *grid = new QGridLayout;

    int r_count = (int)34/4;

    for (uint r=0; r < r_count;r++){
    for (uint c=0; c<4; c++)
    grid->addWidget(new QPushButton("label"),r,c,0,0);

    return app.exec();

  • I have done this code this way. Hope it helps:

    int row=0;
    int numberOfButtons=0;

    while (numberOfButtons<=34)
        for (int f2=0; f2<4; f2++)
            if (numberOfButtons>34)
            QPushButton *button=new QPushButton();
            glayout->addWidget(button, row, f2);


Log in to reply