QWidget::setLayout: Attempting to set QLayout quot;quot; on Widget quot;quot;, which already has a layout(QWidget::setLayout: 试图设置 QLayout 在 Widget“上,它已经有一个布局)
问题描述
我正在尝试通过代码(不是在 Designer 中)手动设置小部件的布局,但我做错了,因为我收到了以下警告:
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 has a layout
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);
}
推荐答案
所以我相信你的问题出在这一行:
So I believe your problem is in this line:
QHBoxLayout *hlayout = new QHBoxLayout(this);
特别是,我认为问题在于将 this
传递到 QHBoxLayout
.因为你打算让这个 QHBoxLayout
不是 this
的顶级布局,所以你不应该将 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);
}
这篇关于QWidget::setLayout: 试图设置 QLayout ""在 Widget“"上,它已经有一个布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:QWidget::setLayout: 试图设置 QLayout ""在 Widget“"上,它已经有一个布局


基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01