How to set QPushButton size in QGridLayout in Qt

Theodore Tang picture Theodore Tang · Nov 10, 2017 · Viewed 11.4k times · Source

I am currently learning qt. And I am trying to build a small GUI program with 81 QPushButton on it.
I want to set those buttons to 9 rows and 9 cols. The best way I can think to implement this layout is using QGridLayout.
This is how that looks like after running:
enter image description here

I tried many ways to change the buttons size, but the buttons size are still remain default.
Here is my code:

void MainWindow::setButtons()
{
    const QSize btnSize = QSize(50, 50);
    for(int i = 0; i < 81; i++) {
        btn[i] = new QPushButton(centralWidget);
        btn[i]->setText(QString::number(i));
        btn[i]->resize(btnSize);
    }

    QGridLayout *btnLayout = new QGridLayout(centralWidget);
    for(int i = 0; i < 9; i++) {
        for(int j = 0; j < 9; j++) {
            btnLayout->addWidget(btn[j + i * 9], 0 + i, j);
            btnLayout->setSpacing(0);
        }
    }
    centralWidget->setLayout(btnLayout);
}

So what can I do to actually change the size of those buttons?
Thanks.

Answer

eyllanesc picture eyllanesc · Nov 10, 2017

If you want to use a fixed size for your widgets you must use setFixedSize():

const QSize btnSize = QSize(50, 50);
for(int i = 0; i < 81; i++) {
    btn[i] = new QPushButton(centralWidget);
    btn[i]->setText(QString::number(i));
    btn[i]->setFixedSize(btnSize);
}

QGridLayout *btnLayout = new QGridLayout(centralWidget);
for(int i = 0; i < 9; i++) {
    for(int j = 0; j < 9; j++) {
        btnLayout->addWidget(btn[j + i * 9], 0 + i, j);
        btnLayout->setSpacing(0);
    }
}
centralWidget->setLayout(btnLayout);

Output:

enter image description here