Qt widget (with layout) space. What is it? How to remove?

烈酒焚心 提交于 2019-12-29 01:41:30

问题


I have written a program that uses widgets as container (for other widgets). Because the contents of the container varies along the program life, the container widget has a layout associated to it so it resizes properly. The problem is that the container seems to consume some space.

In the following program, I have reproduced the problem: I have a group with a few labels, where one of them is included in a container (the widget w -and its layout t- includes the label "what is that extra space?"). My goal is to get the spacing between all labels the same, regardless whether they are in containers or not. (the container should not consume space)

I have also tried to color the different parts of the widgets. Where is my padding? What is the extra space between the widgets (between the blue). And how do I remove it?

 #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();
 }

回答1:


This is contentsMargin

To remove it:

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



回答2:


The space you referring to is a content margin. The docu here describes how the widgets are drawn. To get rid of that extra space you have to call:

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

I believe the end result should look like this:




回答3:


The method I recall to control spacing is to add dedicated QSpacerItem items between the widgets.

But I'm first trying to figure out what w is doing. Why not call g1a_l->addLayout(t); directly?



来源:https://stackoverflow.com/questions/9129324/qt-widget-with-layout-space-what-is-it-how-to-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!