How to set QPushButton size in QGridLayout in Qt
Asked Answered
M

1

8

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.

Montero answered 10/11, 2017 at 15:24 Comment(3)
Maybe use setSizePolicy method? Or use both setMaximumSize() and setMinimumSize() methods to fix sizePash
The size of each button is handled dynamically by the layout. If you change the layout size, the buttons should scale with the layout. How they scale exactly depends on several parameters like the sizePolicy, minimumSize, maximumSize and baseSize. Just setting the size has no real effects for widgets in layout. Can you describe what is the behavior you are looking for?Schaper
@BenjaminT I am just trying to build a minesweeper game to practice Qt because I am very new to this. So I want those buttons stay closely as some squares. After clicking any of them, it will just disappear and show the label beneath. So can you tell me more specific how to set those sizePolicy, minimumSize and so on? ThanksMontero
R
10

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

Rasbora answered 10/11, 2017 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.