如何在PyQt5中填充屏幕?
问题描述:
当我得知在PyQt5
的QHBoxLayout
和QVBoxLayout
,我发现它无法使用他们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
答
QMainWindow
是一个特殊的小部件,因为它有默认的元素,如QStatusBar
,QToolBar
等,如果你想放置一个小部件,你应该把一个小部件,你必须使用setCentralWidget()
方法。
你的情况:
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()
你改变你的鼠标在屏幕的大小? – Trilarion
啊,这意味着改变创建的窗口的大小... – WSY