pyqt5 使用标签管理布局

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_())