为什么我的标签在QHBoxLayout中彼此堆叠? [英] Why are my labels stacking on top of each other inside my QHBoxLayout?
问题描述
就这么简单,我想使用Python的PYQT5在水平框布局内添加两个标签.
Simply enough, I want to add two labels inside an horizontal box layout using Python's PYQT5.
执行此代码时,即使将两个标签添加到QHBoxLayout中也应将它们从左到右放置,但这两个标签会彼此重叠.
When I execute this code, the two labels appear on top of each other, even though adding them to a QHBoxLayout should position them from left to right.
我该如何解决?
- 编译器:Python 3.7.4 32位
- IDE:Visual Studio代码
- 操作系统:Windows 10
我的代码:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class Interface(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'debug'
self.mainLayout = QHBoxLayout()
self.initGUI()
def initGUI(self):
self.setGeometry(0,0,200,200)
self.setFixedSize(self.size())
self.setWindowTitle(self.title)
label1 = QLabel('test 1',self)
label2 = QLabel('test 2',self)
self.mainLayout.addWidget(label1)
self.mainLayout.addWidget(label2)
self.setLayout(self.mainLayout)
self.show()
def close_application(self):
sys.exit()
if __name__ == '__main__':
app = QApplication([])
window = Interface()
sys.exit(app.exec_())
推荐答案
说明:
QMainWindow是具有默认布局的特殊小部件:
Explanation:
QMainWindow is a special widget that has a default layout:
不允许建立其他布局,并明确指出在终端/CMD中执行代码时获得的错误消息:
that does not allow to establish another layout and clearly indicates the error message that is obtained when executing your code in the terminal/CMD:
QWidget::setLayout: Attempting to set QLayout "" on Interface "", which already has a layout
因此,当未建立布局时,它不会处理QLabels的位置,并且当您作为父级传递给window- self
时,两者都将在窗口的左上角位置进行设置.
So when the layout is not established, it does not handle the position of the QLabels, and you, when passing as a parent to window-self
, both will be set in the window in the top-left position.
文档指出,您必须创建一个用作容器的中央小部件,然后设置布局:
As the docs points out, you must create a central widget that is used as a container and then set the layout:
def initGUI(self):
self.setGeometry(0,0,200,200)
self.setFixedSize(self.size())
self.setWindowTitle(self.title)
central_widget = QWidget() # <---
self.setCentralWidget(central_widget) # <---
label1 = QLabel('test 1')
label2 = QLabel('test 2')
self.mainLayout.addWidget(label1)
self.mainLayout.addWidget(label2)
central_widget.setLayout(self.mainLayout) # <---
self.show()
这篇关于为什么我的标签在QHBoxLayout中彼此堆叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!