2017-08-11 43 views
0

當我得知在PyQt5QHBoxLayoutQVBoxLayout,我發現它無法使用他們QMainWindow。他們必須依靠QWidget。這裏是我的代碼:如何在PyQt5中填充屏幕?

import sys 
from PyQt5.QtWidgets import QApplication,QMainWindow,QWidget,QLabel,QHBoxLayout,QVBoxLayout 

class Example(QMainWindow) : 
    def __init__(self) : 
     super().__init__() 
     self.build_inter() 

    def build_inter(self) : 
     self.setGeometry(300,300,300,220) 

     self.root_widget=QWidget(self) 
     self.root_widget.resize(self.size()) 

     self.name_label=QLabel("Wang Suyu",self.root_widget) 
     self.age_label=QLabel("14",self.root_widget) 

     hbox=QHBoxLayout() 
     hbox.addStretch(1) 
     hbox.addWidget(self.name_label) 
     hbox.addWidget(self.age_label) 
     vbox=QVBoxLayout() 
     vbox.addStretch(1) 
     vbox.addLayout(hbox) 

     self.root_widget.setLayout(vbox) 

     self.show() 

if __name__ == '__main__': 
    app=QApplication(sys.argv) 
    example=Example() 
    sys.exit(app.exec_()) 

然而,作爲一個小工具,我也沒辦法讓QWidget自動填充屏幕,因爲我用鼠標更改了屏幕的大小。root_widget和兩個標籤將保持原始。

我該怎麼辦?我真的不想改變超類的Example

+0

你改變你的鼠標在屏幕的大小? – Trilarion

+0

啊,這意味着改變創建的窗口的大小... – WSY

回答

0

QMainWindow是一個特殊的小部件,因爲它有默認的元素,如QStatusBarQToolBar等,如果你想放置一個小部件,你應該把一個小部件,你必須使用setCentralWidget()方法。

enter image description here

你的情況:

class Example(QMainWindow) : 
    def __init__(self) : 
     super().__init__() 
     self.build_inter() 

    def build_inter(self) : 
     self.setGeometry(300,300,300,220) 

     self.root_widget=QWidget(self) 
     self.setCentralWidget(self.root_widget) 

     self.name_label=QLabel("Wang Suyu",self.root_widget) 
     self.age_label=QLabel("14",self.root_widget) 

     hbox=QHBoxLayout() 
     hbox.addStretch(1) 
     hbox.addWidget(self.name_label) 
     hbox.addWidget(self.age_label) 
     vbox=QVBoxLayout() 
     vbox.addStretch(1) 
     vbox.addLayout(hbox) 
     self.root_widget.setLayout(vbox) 
     self.show() 
+0

謝謝你的偉大答案!(PS:好圖片) – WSY

+0

這是該文檔的圖像:http://doc.qt.io/qt-5 /qmainwindow.html – eyllanesc