Python PyQt5, How can I make QGridLayout rows close together and align to top?

489 Views Asked by At

I have a PyQt5 MainWindow which contains just a QGridLayout. the QGridLayout contains only two rows of QLabel widget just for test. enter image description here But the two rows of QLabel is far from together and loose. How can I make rows close together and align the QGridLayout at top of MainWindow? Code here, thanks!

class MainWindow(Ui_MainWindow, QMainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.gridLayout.addWidget(QLabel('First Row'), 0, 0)
        self.gridLayout.addWidget(QLabel('Second Row,oh! Ugly'), 1, 0)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
1

There are 1 best solutions below

0
SimoN SavioR On
    # => for align items
    self.gridLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
    # => row spacing
    self.gridLayout.setVerticalSpacing(5)

or you can use

    self.gridLayout.setSpacing(5) # => both of vertical and horizontal
    self.gridLayout.setHorizontalSpacing(5) # => only horizontal-columns