我正在尝试通过代码手动设置窗口小部件(不在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);
}
答案 0 :(得分:16)
所以我相信你的问题就在这一行:
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);
}
答案 1 :(得分:6)
问题是您正在创建父级为this
的布局。当您这样做时,它将布局设置为this
的主要布局。因此,调用setMainLayout()
是多余的。