7

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Theodore Tang
  • 831
  • 2
  • 21
  • 42
  • Maybe use setSizePolicy method? Or use both setMaximumSize() and setMinimumSize() methods to fix size – Andrey Semenov Nov 10 '17 at 15:29
  • 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? – Benjamin T Nov 10 '17 at 15:34
  • @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? Thanks – Theodore Tang Nov 10 '17 at 15:49

1 Answers1

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241