[英]pyqt5 managing layout with labels
我試圖在布局中添加幾個標簽,並且這些項目需要相鄰。
下面的代碼使它們相鄰,但位於布局的中間。 我希望這些標簽在頂部。
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QDialog, QGridLayout, QLabel, QLineEdit
from PyQt5.Qt import QHBoxLayout, QWindow, QMainWindow, QVBoxLayout
class Example(QMainWindow):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.initUI()
def initUI(self):
vlayout = QVBoxLayout()
hlayout = QHBoxLayout()
widget = QWidget()
widget.setLayout(hlayout)
a1 = QLabel('label1')
a2 = QLabel('label2')
hlayout.addWidget(a1)
hlayout.addWidget(a2)
hlayout.addStretch(2)
vlayout.addLayout(hlayout)
vlayout.addStretch(1)
self.setCentralWidget(widget)
self.setGeometry(500, 500, 500, 500)
self.setWindowTitle('Lines')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
# ex.show()
sys.exit(app.exec_())
布局必須在小部件內部,但是在您的情況下, QVBoxLayout
不會由任何小部件表示。
這個想法是您具有以下結構:
widget
└── vlayout
└── hlayout
├── a1
└── a2
使用該結構,我們可以得到以下內容:
import sys
from PyQt5 import QtCore, QtWidgets
class Example(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.initUI()
def initUI(self):
widget = QtWidgets.QWidget()
vlayout = QtWidgets.QVBoxLayout(widget)
hlayout = QtWidgets.QHBoxLayout()
a1 = QtWidgets.QLabel('label1', )
a2 = QtWidgets.QLabel('label2')
hlayout.addWidget(a1)
hlayout.addWidget(a2)
hlayout.addStretch()
vlayout.addLayout(hlayout)
vlayout.addStretch()
self.setCentralWidget(widget)
self.setGeometry(500, 500, 500, 500)
self.setWindowTitle('Lines')
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Example()
# ex.show()
sys.exit(app.exec_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.