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

发布了23 篇原创文章 · 获赞 4 · 访问量 9964

猜你喜欢

转载自blog.csdn.net/hxp1994/article/details/103882980
今日推荐