问题
Simply enough, I want to add two labels inside an horizontal box layout using Python's PYQT5.
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.
How can I fix this?
- Compiler : Python 3.7.4 32 bit
- IDE : Visual Studio Code
- OS : Windows 10
my code:
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_())
回答1:
Explanation:
QMainWindow is a special widget that has a default layout:
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
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.
Solution:
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()
来源:https://stackoverflow.com/questions/58123629/why-are-my-labels-stacking-on-top-of-each-other-inside-my-qhboxlayout