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

 

 

 

發佈了21 篇原創文章 · 獲贊 4 · 訪問量 7559
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章