Please nominate your Qt Champions for 2021!

[SOLVED] QGridLayout does not lay out properly?

  • Hi everyone,

    newbie here, hope you can help me.
    I need to arrange the following widgets in a grid with 3 columns:
    the first (header) row will have 3 bold labels,
    the subsequent rows will have buttons in the first column, and short labels in 2nd and 3rd columns, that would become visible when the button is pressed.
    I create this in the code (not using QT Creator) as follows:

    @QGridLayout *gridLayout = new QGridLayout(this);

    gridLayout->addWidget(createHeaderLabel("Buttons"), 0, 0);
    gridLayout->addWidget(createHeaderLabel("Labels"), 0, 1);
    gridLayout->addWidget(createHeaderLabel("LabelsToo"), 0, 2);

    for (int row = 1; row < 10; row++)
    QPushButton* btn = new QPushButton(QString::number(row), this);
    btn->setFixedSize(70, 20);
    gridLayout->addWidget(btn, row, 0);

        QLabel* lbl1 = new QLabel(this);
        gridLayout->addWidget(lbl1, row, 1);
        QLabel* lbl2 = new QLabel(this);
        gridLayout->addWidget(lbl2, row, 2);



    and here is createHeaderLabel() implementation:

    @QLabel* createHeaderLabel(QString name)
    QLabel* lbl = new QLabel(name);
    QFont font = lbl->font();

    return lbl;


    When the button is pressed, the 2 labels in the same row will display their text which is a 1-3 characters long. (I omitted this part of code as I think it is not relevant here).
    For some reason, when I run this, the first two columns are aligned nicely, the buttons are centered under the 1st header label; and when a button is pressed, the label in the 2nd column would appear centered under the 2nd header label; but in the third column, the header label is not aligned with the labels underneath.
    I tried to set fixed size to the labels, but it didn't help. Could you please point me in the right direction?

    Thank you,

Log in to reply