QT在构造函数中写的控件不显示(按钮不显示)问题

一、问题:

有时间你会发现你在新建的工程中构造函数里面编写按钮等控件去初始化后运行发现窗口一片空白,什么都不显示,是什么原因导致呢?

二、可能出现的原因:

1、你新建的工程师MainWindow子类工程,没有设置父窗口。

2、没有将控件的父窗口设置成自己定义的widget。

eg:

#include<QMainWindow>

QMainWindow::QMainWindow(QMainWindow*parent) :
    QMainWindow(parent),
    ui(new Ui::QMainWindow)
{
     ui->setupUi(this);
     QPushButton* button_1 = new QPushButton("add");
     QPushButton* button_1 = new QPushButton("del");
}

三、运行结果:

一个空白窗体

四、解决方法:

解决方法1:

给按钮控件设置父窗口:QWidget,并且把按钮添加到父窗口中。

#include<QMainWindow>
#include<QPushButton>
#include<QHBoxLayout>

QMainWindow::QMainWindow(QMainWindow*parent) :
    QMainWindow(parent),
    ui(new Ui::QMainWindow)
{
     ui->setupUi(this);
     QWidget* w = new QWidget();
     this->setCentralWidget(w);
     QHBoxLayout* hLayout = new QHBoxLayout();
     QPushButton* button_1 = new QPushButton("add");
     QPushButton* button_1 = new QPushButton("del");
     hLayout->addWidget(button_1);
     hLayout->addWidget(button_2);
     w->setLayout(hLayout);
}

解决方法2:

直接建立QWidget的工程

#include<QWidget>
#include<QPushButton>
#include<QVBoxLayout>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
        ui->setupUi(this);

        QPushButton* button_1 = new QPushButton("add");
        QPushButton* button_2 = new QPushButton("del");
        QHBoxLayout* hLayout = new QHBoxLayout();
        QVBoxLayout* vLayout = new QVBoxLayout();

        hLayout->addWidget(button_1);
        hLayout->addWidget(button_2);
        this->setLayout(hLayout);
}

解决方法3:

#include<QMainWindow>
#include<QPushButton>
#include<QHBoxLayout>

QMainWindow::QMainWindow(QMainWindow*parent) :
    QMainWindow(parent),
    ui(new Ui::QMainWindow)
{
     ui->setupUi(this);
    
    
     QPushButton* button_1 = new QPushButton("add");
     QPushButton* button_1 = new QPushButton("del");
     button_1->setParent(this);
     button_2->setParent(this);
     button_2->move(300,100);
    
}

五、结论:

想窗体中的控件可见,你必须将该窗体设置成这些控件的父窗口。

怎么让新建的工程存在父子关系:

(1)把控件添加到布局管理器中,QT会自动生成父子关系。比如解决方法1,2,可以直接添加按钮到布局管理器中,不需要再QWdiget,这里为了说清楚添加了,可以不需要。

(2)假如新建的QMainWindow,需要自己指定控件的父窗体。比如解决方法3

 

 

 

  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值