Qt QGridLayout元素的宽度和高度相同,

时间:2018-07-30 13:07:20

标签: qt

我正在尝试QT重做WPF项目。我想使用QGridLayout布局按钮,每个按钮的尺寸为64x64 px。但是,网格似乎并不尊重这些尺寸,我确定64x64不会那么小。而且,这些元素之间也存在巨大差距。我如何才能更紧密地包装这些按钮,并使它们全部统一为64 x 64像素?最好甚至将列和行数限制为4和window_height / 64

代码:

#include "productbuttongrid.h"

#include <QPushButton>

ProductButtonGrid::ProductButtonGrid(QWidget *parent): QGridLayout(parent)
{

    QPushButton *button = new QPushButton("Toode", parent);
    button->setFixedSize(64,64);

    QPushButton *button2 = new QPushButton("Toode2", parent);
    button2->setFixedSize(64,64);

    QPushButton *button3 = new QPushButton("Toode2", parent);
    button3->setFixedSize(64,64);
    QPushButton *button4 = new QPushButton("Toode2", parent);
    button4->setFixedSize(64,64);
    QPushButton *button5 = new QPushButton("Toode2", parent);
    button5->setFixedSize(64,64);

    this->addWidget(button,0,0);
    this->addWidget(button2,0,1);
    this->addWidget(button3,0,2);
    this->addWidget(button4,0,3);
    this->addWidget(button5,1,0);

}

输出的内容,而不是64x64的按钮:它们看起来也太小了,无法达到64x64

enter image description here

1 个答案:

答案 0 :(得分:2)

如果您希望按钮紧密隔开,那么您需要为QGridLayout提供一些使用给定的额外空间的方法。

在这种情况下,最简单的方法就是在按钮的下方和右侧创建一个虚拟的行和列,并允许它们拉伸。因此,只需添加...

setRowStretch(rowCount(), 1);
setColumnStretch(columnCount(), 1);

ProductButtonGrid构造函数的末尾。

如果要使按钮网格居中对齐,则请安排在按钮的上方,下方,左侧,右侧具有可拉伸的“额外”行/列。

您可能还希望使用QGridLayout::setSpacing来消除通常的物品间距。