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:
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.
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: