Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set QPushButton size in QGridLayout in Qt

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.

like image 879
Theodore Tang Avatar asked Nov 10 '17 15:11

Theodore Tang


1 Answers

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

like image 132
eyllanesc Avatar answered Nov 10 '22 01:11

eyllanesc