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

问题描述

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

在这里插入图片描述

代码如下:

#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()
{
}

错误如下:
在这里插入图片描述
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()
{
}


运行结果:

在这里插入图片描述

解决。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值