2017-08-04 27 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

相关问题