如何使用Qt减少小部件之间的距离和窗口大小?

时间:2018-08-14 12:32:45

标签: c++ qt qt5

我目前拥有的东西:

Current window

我想要什么:

Wanted window

对于那些无法查看图像的人;小部件之间会以某种程度的余量分布。我想让它们尽可能的靠近。如何将小部件挤压得更近一些?

我已经尝试过:
主窗口,布局和小部件对象上的setFixedSize(sizeHint());setSizeConstraint(QLayout::SetFixedSize);。似乎没有任何作用。

另外,我也很感激:
(使标签更靠近lineEdit)

我正在使用Windows和Qt 5.11.1(64位)。
窗口构造器代码:

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
    widget = new QWidget();
    label = new QLabel(tr("Enter your name:"));
    nameLine = new QLineEdit;
    nameLine->setMinimumWidth(250);
    label->setBuddy(nameLine);

    okButton = new QPushButton (tr("Ok"));
    clearButton = new QPushButton (tr("Clear"));

    connect(okButton, SIGNAL(clicked()), this, SLOT(message()));
    connect(clearButton, SIGNAL(clicked()), this, SLOT(clear()));

    QGridLayout *grid = new QGridLayout;
    grid->addWidget(label,0,0);
    grid->addWidget(nameLine,1,0);
    grid->addWidget(okButton,0,1);
    grid->addWidget(clearButton,1,1);

    widget->setLayout(grid);

    setWindowTitle(tr("Leo v0.0"));
    setCentralWidget(widget);
}

1 个答案:

答案 0 :(得分:3)

可能的解决方案是用QVBoxLayout建立一个addStretch()

QVBoxLayout *vlay = new QVBoxLayout;
QGridLayout *grid = new QGridLayout;
grid->addWidget(label, 0, 0);
grid->addWidget(nameLine, 1, 0);
grid->addWidget(okButton, 0, 1);
grid->addWidget(clearButton, 1, 1);
vlay->addLayout(grid);
vlay->addStretch();
widget->setLayout(vlay);
setCentralWidget(widget);