Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QWidget::setLayout: Attempting to set QLayout "" on Widget "", which already has a layout

I'm trying to set the layout of a widget manually through code (not in Designer), but I'm doing something wrong, because I get this warning:

QWidget::setLayout: Attempting to set QLayout "" on Widget "", which already has a layout

And also the layout is messed up (the label is at the top, instead of the bottom).

This is an example code that reproduces the problem:

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    QLabel *label = new QLabel("Test", this);
    QHBoxLayout *hlayout = new QHBoxLayout(this);
    QVBoxLayout *vlayout = new QVBoxLayout(this);
    QSpacerItem *spacer = new QSpacerItem(40, 20, QSizePolicy::Fixed);
    QLineEdit *lineEdit = new QLineEdit(this);
    hlayout->addItem(spacer);
    hlayout->addWidget(lineEdit);
    vlayout->addLayout(hlayout);
    vlayout->addWidget(label);
    setLayout(vlayout);
}
like image 354
user1369511 Avatar asked May 09 '12 15:05

user1369511


People also ask

How do I add a layout to Qwidget?

To set the layout on the parent widget, you need to drop the ->layout() : twInputMethodsTabs->value(1). first->addLayout(hblParams); Note that since you are now adding an empty layout to the widget, any widgets current in the previous layout will be lost, so you may need to re-add the widgets to the layout.

What is QVBoxLayout?

The QVBoxLayout class lines up widgets vertically. This class is used to construct vertical box layout objects. See QBoxLayout for details.


2 Answers

So I believe your problem is in this line:

QHBoxLayout *hlayout = new QHBoxLayout(this);

In particular, I think the problem is passing this into the QHBoxLayout. Because you intend for this QHBoxLayout to NOT be the top level layout of this, you should not pass this into the constructor.

Here's my re-write that I hacked into a test app locally and seems to work great:

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    QLabel *label = new QLabel("Test");
    QHBoxLayout *hlayout = new QHBoxLayout();
    QVBoxLayout *vlayout = new QVBoxLayout();
    QSpacerItem *spacer = new QSpacerItem(40, 20, QSizePolicy::Fixed);
    QLineEdit *lineEdit = new QLineEdit();
    hlayout->addItem(spacer);
    hlayout->addWidget(lineEdit);
    vlayout->addLayout(hlayout);
    vlayout->addWidget(label);
    setLayout(vlayout);
}
like image 194
brakeley Avatar answered Sep 22 '22 16:09

brakeley


The problem is that you are creating layouts with a parent of this. When you do that, it sets the layout to be the main layout of this. Thus, it is redundant to call setMainLayout().

like image 37
Anthony Avatar answered Sep 21 '22 16:09

Anthony