QWidget :: setLayout:试图在Widget上设置QLayout"",它已经有了一个布局

use*_*511 14 c++ layout qt widget

我试图通过代码手动设置窗口小部件(不在Designer中),但是我做错了,因为我收到了这个警告:

QWidget :: setLayout:试图在Widget上设置QLayout"",它已经有了一个布局

而且布局也搞砸了(标签位于顶部,而不是底部).

这是一个重现问题的示例代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

小智 16

所以我相信你的问题就在这一行:

QHBoxLayout *hlayout = new QHBoxLayout(this);
Run Code Online (Sandbox Code Playgroud)

特别是,我认为问题是this进入了QHBoxLayout.因为您打算QHBoxLayout不将其作为顶级布局this,所以不应该传递this给构造函数.

这是我的重写,我在本地入侵了一个测试应用程序,似乎工作得很好:

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);
}
Run Code Online (Sandbox Code Playgroud)


Ant*_*ony 6

问题是您正在创建父级为的布局this.当你这样做时,它将布局设置为主要布局this.因此,呼叫是多余的setMainLayout().