2017-08-04 112 views
0

我想在qt5中使用佈局,但在Visual Studio 2015中佈局不起作用?qt5佈局在Visual Studio 2015中不起作用?

這裏是我的代碼:

layout.h代碼

#ifndef LAYOUT_H 
#define LAYOUT_H 

#include <QtWidgets/QMainWindow> 
#include "ui_layout.h" 

class layout : public QMainWindow 
{ 
    Q_OBJECT 

public: 
    layout(QWidget *parent = 0); 
    ~layout(); 

private: 
    Ui::layoutClass ui; 
}; 

#endif // LAYOUT_H 

的main.cpp

#include "layout.h" 
#include <QtWidgets/QApplication> 
#include <QtWidgets/QPushButton> 
#include <QtWidgets/QHBoxLayout> 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    layout w; 
    QHBoxLayout hb; 
    QPushButton b("button 0"); 
    QPushButton b1("button 1"); 

    hb.addWidget(&b); 
    hb.addWidget(&b1); 

    w.setLayout(&hb); 
    w.show(); 
    return a.exec(); 
} 

這裏是我的結果: enter image description here

如何解決這個問題?

+0

是什麼佈局? – eyllanesc

+0

@eyllanesc QHBoxLayout和QVBoxLayout – lens

+0

QVBoxLayout和QHBoxLayout沒有show方法。 – eyllanesc

回答

1

QMainWindow是一個特殊的窗口小部件,因爲它具有像QStatusbar,QMenuBar等默認窗口小部件。使用這個窗口小部件時,我們必須將新的元素放置在中央窗口小部件中。

enter image description here

因此,我們必須分配一個小工具,將是我們centralWidget,然後到這一點,我們添加的佈局如下圖所示:

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    layout w; 
    w.setCentralWidget(new QWidget); 


    QHBoxLayout hb; 
    QPushButton b("button 0"); 
    QPushButton b1("button 1"); 

    hb.addWidget(&b); 
    hb.addWidget(&b1); 

    w.centralWidget()->setLayout(&hb); 
    w.show(); 

    return a.exec(); 
} 
+0

這個解決方案可以解決我的問題,但我不完全理解爲什麼我們必須使用centralWidget。你能給我提供一些文章或文件嗎?我會閱讀這些信息。 – lens

+0

我答案的第一個單詞有一個鏈接,這是主要文檔,但是如果您還沒有看到它,那麼這是:http://doc.qt.io/qt-5/qmainwindow.html。請不要忘記標記我的答案是正確的。 – eyllanesc

相關問題