简体   繁体   English

如何在Qt中的QGridLayout中设置QPushButton大小

[英]How to set QPushButton size in QGridLayout in Qt

I am currently learning qt. 我正在学习qt。 And I am trying to build a small GUI program with 81 QPushButton on it. 我正在尝试使用81 QPushButton构建一个小型GUI程序。
I want to set those buttons to 9 rows and 9 cols. 我想将这些按钮设置为9行和9列。 The best way I can think to implement this layout is using QGridLayout . 我能想到实现这种布局的最好方法是使用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() : 如果要为小部件使用固定大小,则必须使用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: 输出:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM