为什么 QGridLayout 不适用于 QLabel

why the QGridLayout do not work for QLabel

我在我的项目中使用QGridLayout,代码是:


import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=parent)

        widget = QWidget()
        self.setCentralWidget(widget)
        layout = QGridLayout()
        widget.setLayout(layout)

        lay1 = QVBoxLayout()
        lay1Header = QHBoxLayout()
        lay1Header.addWidget(QLabel('lay1'))
        lay1.addLayout(lay1Header)
        label1 = QLabel('label1')
        label1.setStyleSheet('background: rgb(255, 0, 0)')
        lay1.addWidget(label1)

        lay2 = QVBoxLayout()
        lay2Header = QHBoxLayout()
        lay2Header.addWidget(QLabel('lay2'))
        lay2Header.addWidget(QLineEdit())
        lay2.addLayout(lay2Header)
        label2 = QLabel('label2')
        label2.setStyleSheet('background: rgb(0, 0, 255)')
        lay2.addWidget(label2)

        layout.addLayout(lay1, 0, 0, 1, 1)
        layout.addLayout(lay2, 0, 1, 1, 1)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

结果是:

我的环境是:

win 10
anaconda
pyqt5 5.14.0

如何让label1/label2的大小一样?

QGridLayout 中项目的大小取决于列或行中的所有项目,而不仅仅是其中之一。所以对于这种情况,解决方案是为列设置相同的对齐因子,并将第一个 QLabel 的高度设置为 QLineEdit 的高度:

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=parent)

        widget = QWidget()
        self.setCentralWidget(widget)
        layout = QGridLayout(widget)

        lbl1 = QLabel("lay1")
        lay1 = QVBoxLayout()
        lay1Header = QHBoxLayout()
        lay1Header.addWidget(lbl1)
        lay1.addLayout(lay1Header)
        label1 = QLabel("label1")
        label1.setStyleSheet("background: rgb(255, 0, 0)")
        lay1.addWidget(label1)

        le1 = QLineEdit()
        lay2 = QVBoxLayout()
        lay2Header = QHBoxLayout()
        lay2Header.addWidget(QLabel("lay2"))
        lay2Header.addWidget(le1)
        lay2.addLayout(lay2Header)
        label2 = QLabel("label2")
        label2.setStyleSheet("background: rgb(0, 0, 255)")
        lay2.addWidget(label2)

        layout.addLayout(lay1, 0, 0, 1, 1)
        layout.addLayout(lay2, 0, 1, 1, 1)

        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)
        lbl1.setFixedHeight(le1.sizeHint().height())