> 文章列表 > Qt——QLayout: Attempting to add QLayout ““ to XXX““, which already has a layout

Qt——QLayout: Attempting to add QLayout ““ to XXX““, which already has a layout

Qt——QLayout: Attempting to add QLayout ““ to XXX““, which already has a layout

问题描述

我在编写如下的 demo 时,运行代码产生了问题。

Qt——QLayout: Attempting to add QLayout ““ to XXX““, which already has a layout

代码如下:

#include "networkinformation.h"
#include <QGridLayout>NetworkInformation::NetworkInformation(QWidget *parent): QMainWindow(parent){hostNameLabel = new QLabel(tr("主机名:"));hostNameLineEdit = new QLineEdit;ipLabel = new QLabel(tr("IP地址:"));ipLineEdit = new QLineEdit;detailBtn = new QPushButton(tr("详细"));QGridLayout * mainLayout = new QGridLayout(this);mainLayout->addWidget(hostNameLabel,0,0);mainLayout->addWidget(hostNameLineEdit,0,1);mainLayout->addWidget(ipLabel,1,0);mainLayout->addWidget(ipLineEdit,1,1);mainLayout->addWidget(detailBtn,2,0,1,2);
}NetworkInformation::~NetworkInformation()
{
}

错误如下:
Qt——QLayout: Attempting to add QLayout ““ to XXX““, which already has a layout
QLayout: Attempting to add QLayout "" to NetworkInformation "", which already has a layout

言下之意是 已经存在一个布局了,不能再设置新的布局。。。

解决方法

通过 Google 之后发现,由于我的基类是 QMainWindowQMainWindow是自带一个布局的,并且这个布局我们是不能移除的。

由于 QMainWindow是有不同的区域的(主要区域,tool区,dock区,status区)。那么我就可以先用一个 widget设置到想要设置布局的区域,比如 central。然后再设置这个 widget的布局即可。

代码:

#include "networkinformation.h"
#include <QGridLayout>NetworkInformation::NetworkInformation(QWidget *parent): QMainWindow(parent){QWidget * widget = new QWidget();this->setCentralWidget(widget);hostNameLabel = new QLabel(tr("主机名:"));hostNameLineEdit = new QLineEdit;ipLabel = new QLabel(tr("IP地址:"));ipLineEdit = new QLineEdit;detailBtn = new QPushButton(tr("详细"));QGridLayout * mainLayout = new QGridLayout;mainLayout->addWidget(hostNameLabel,0,0);mainLayout->addWidget(hostNameLineEdit,0,1);mainLayout->addWidget(ipLabel,1,0);mainLayout->addWidget(ipLineEdit,1,1);mainLayout->addWidget(detailBtn,2,0,1,2);widget->setLayout(mainLayout);
}NetworkInformation::~NetworkInformation()
{
}

运行结果:

Qt——QLayout: Attempting to add QLayout ““ to XXX““, which already has a layout

解决。