Qiang Zhang
Qiang Zhang

Reputation: 952

why the QGridLayout do not work for QLabel

I am using QGridLayout in my project, and the code is:


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

And the result is:

enter image description here

My environment is:

win 10
anaconda
pyqt5 5.14.0

How can I make the size of label1/label2 the same?

Upvotes: 1

Views: 80

Answers (1)

eyllanesc
eyllanesc

Reputation: 244359

The size of the items in a QGridLayout depends on all the items in the column or row, not just one of them. So for this case the solution is to set the same alignment factor for the columns and set the height of the first QLabel to be that of the 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())

Upvotes: 1

Related Questions