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

标签 c++ qt layout widget

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

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

而且布局也很乱(标签在顶部,而不是底部)。

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

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 *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);
}

关于c++ - QWidget::setLayout: 试图在 Widget ""上设置 QLayout "",它已经有一个布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10519006/

相关文章:

c++ - Eclipse:编译,但 CODAN(内部代码分析器)为 C++ 11 <includes> 中的函数提供错误

qt - 在槽函数运行时显示一个 "Please wait..."框

java - 如何在父线性布局下方添加相对布局?

java - 在 GridBagLayout 中设置 columnWidth 和 rowHeight

C++ OpenMP exit while loop inside a parallel for

c++ - 如何在 3D 物体(如球体)上绘制文字

c++ - C++程序中的选项

qt - 从 QTextEdit 中删除行/ block

c++ - 用 qt(5) 绘制 Tiled map 的最佳方法是什么?

CSS 框图像 - 布局问题