Qt小部件(带布局)空间。这是什么?如何移除?

4
我写了一个程序,使用小部件作为容器(用于其他小部件)。由于容器的内容在程序生命期内变化,因此容器小部件具有相关的布局,以便它可以适当地调整大小。 问题是容器似乎会占用一些空间。
在下面的程序中,我复制了这个问题:我有一个带有几个标签的组,其中一个标签包含在一个容器中(小部件w -和其布局t- 包括标签“那是什么额外的空间?”)。
我的目标是获得所有标签之间的间距相同,无论它们是否在容器中(容器不应该占用空间)。
我还尝试着将小部件的不同部分着色。我的填充在哪里?小部件之间的额外空间是什么(蓝色之间)?如何去除它?
 #include <QApplication>
 #include <QtCore>
 #include <QMainWindow>
 #include <QGroupBox>
 #include <QHBoxLayout>
 #include <QLabel>
 #include <QMdiArea>
 #include <QMdiSubWindow>

 #include <stdlib.h>

 QMdiArea* g1;
 QGroupBox* g1a;

 int main(int argc, char *argv[])
 {
    QApplication app(argc, argv);
    QMainWindow* main_window = new(QMainWindow);
    main_window->resize(200, 200);
    main_window->setWindowTitle("Hello");

    g1a = new QGroupBox("G1A", g1);
    QVBoxLayout *g1a_l = new QVBoxLayout(g1a);
    g1a_l->setSpacing(0);
    main_window->setCentralWidget(g1a);

    g1a_l->addWidget((QLabel*)new QLabel(" Nice Label1"));
    g1a_l->addWidget((QLabel*)new QLabel(" Nice Label2"));
    QWidget* w=new QWidget(0);
    w->setStyleSheet( "border: 2 solid blue; padding: 2 solid yellow;" );
    QVBoxLayout* t=new QVBoxLayout(w);
    t->setSpacing(0);
    t->addWidget(new QLabel("What is that extra space??",w));

    g1a_l->addWidget(w);
    g1a_l->addWidget((QLabel*)new QLabel(" Nice Label3"));
    g1a_l->addWidget((QLabel*)new QLabel(" Nice Label4"));

    //sub_window->adjustSize();
    main_window->show(); //How to I get that to recaclulate the size of its contents?
    return app.exec();
 }

为什么?完整的源代码已包含。构建并查看。 - user336063
可能是Removing extra spacing around QWidget的重复问题。 - Trilarion
3个回答

7

这是内容边距

要将其移除:

t->setContentsMargins(0,0,0,0);

2

您所指的空间是内容边距。这里的文档描述了小部件的绘制方式。要消除那个额外的空间,您需要调用:

widget->setContentsMargins(0, 0, 0, 0);

我相信最终结果应该是这样的:

enter image description here


0

我记得控制间距的方法是在小部件之间添加专用的QSpacerItem项目。

但我首先想弄清楚w在做什么。为什么不直接调用g1a_l->addLayout(t);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接