QWidget::setLayout: 尝试在已经有布局的窗口部件""上设置QLayout ""。

17

我正在尝试通过代码手动设置小部件的布局(而不是在设计师中设置),但我做错了什么,因为我收到以下警告:

QWidget::setLayout: 尝试在已经有布局的小部件“”上设置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);
}

哇,仅仅因为一个简单的错误就要做这么多工作: QHBoxLayout *buttonLayout = new QHBoxLayout();而不是: QHBoxLayout *buttonLayout = new QHBoxLayout(this); - user1369511
在 PySide 中与我的代码相同,将 hl = QtGui.QHBoxLayout(self) 更改为 hl = QtGui.QHBoxLayout()。 - gseattle
2个回答

18

所以我认为你的问题出在这行代码上:

QHBoxLayout *hlayout = new QHBoxLayout(this);

我认为问题主要出现在将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);
}

7
问题在于您正在使用父级为this创建布局。这样做会将布局设置为this的主要布局。因此,调用setMainLayout()是多余的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接