Important: Please read the Qt Code of Conduct -

QGroupBox does not fit into layouts

  • Hi
    I have a QDialog in which is a QTabWidget. In this widget should be some groups. One group is "Settings" that consists of a qlabel and a qlineedit per row. I will add more pairs later. I want to have a border arround this group so I thought qgroupbox might be proper. I simply dont get behind the qgroupbox magic... I dont know how to shrink the Settings-qgroupbox to the size of the label and the lineedit. I managed to shrink it vertically but it does not horizontally.
    Here is an image how it looks current.

    GeneralTab::GeneralTab(QWidget *parent)
    	QLabel *videoDeviceLabel = new QLabel("Video Device:");
    	QLineEdit *videoDeviceValueLabel = new QLineEdit("/dev/video0");
    	QHBoxLayout *horizontalLayout = new QHBoxLayout;
    	QGroupBox *box = new QGroupBox("Settings");
    	QVBoxLayout *mainLayout = new QVBoxLayout;

    any ideas?

  • it's not a problem of the groupbox but of the layout you put it in


        QVBoxLayout *mainLayout = new QVBoxLayout;


        QGridLayout *mainLayout = new QGridLayout ;
        mainLayout->additem(new QSpacerItem(10,10,QSizePolicy::Expanding,QSizePolicy::Preferred),0,1);
    mainLayout->additem(new QSpacerItem(10,10,QSizePolicy::Preferred,QSizePolicy::Expanding),1,0);

  • Ok, now I get this:
    The GroupBox seems to horizontally take half of the dialog but does not shrink to the end
    of the qlineedit.

  • I just tried a new project and just by using the form editor and that was so easy:

    Its just a button and a lineedit in a horizontal layout in a group box. Why cant I do this programmatically?

  • Lifetime Qt Champion


    Since you want a QLabel + QLineEdit, why not use QFromLayout ?

    That should also simplify size handling.

    Hope it helps

  • remove horizontalLayout->addStretch(1); that is what is taking space after the line edit

  • @SGaist thank you, I took QFormLayout into account.
    @VRonin also thank you!
    I can not believe that it would take so much code to get this done...
    After starting over and over again I came up with this:

    GeneralTab::GeneralTab(QWidget *parent)
    			QLineEdit *lineEdit = new QLineEdit("/dev/video0");
    			QGroupBox *groupBox = new QGroupBox("Settings",this);
    			QFormLayout *formLayout = new QFormLayout(groupBox);
    			formLayout->addRow("Video Device: ",lineEdit);

    and this looks exactly what I wanted, two widgets with a nice group box border sized to minimal space usage:
    I dont really know If this code is correct or might produce trouble but at least I dont find any errors at the moment.