15

我正在尝试通过代码(而不是在 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);
}
4

2 回答 2

16

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

QHBoxLayout *hlayout = new QHBoxLayout(this);

特别是,我认为问题正在传递thisQHBoxLayout. 因为您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);
}
于 2012-05-09T16:02:23.223 回答
6

问题是您正在使用this. 当你这样做时,它会将布局设置为this. 因此,调用 是多余的setMainLayout()

于 2012-05-09T15:51:43.417 回答