Viswa
Viswa

Reputation: 174

How to add stretch for QGridLayout in PyQt5?

I created widgets in a grid-layout. The widgets are stretching based on the window. Is it possible to avoid the stretching and align them as shown in picture below? I created a code to achieve this, but I feel it is not a straightforward solution. If there are any better solutions to achieve this, please share them.

Grid layout result:

from PyQt5.QtWidgets import *
app =QApplication([])
window=QWidget()
GL=QGridLayout(window)
GL.addWidget(QPushButton('R1C1'),0,0)
GL.addWidget(QPushButton('R1C2'),0,1)
GL.addWidget(QPushButton('R2C1'),1,0)
GL.addWidget(QPushButton('R1C1'),1,1)
window.showMaximized()
app.exec_()

enter image description here

Required Result:

enter image description here

My code:

from PyQt5.QtWidgets import *
app =QApplication([])
window=QWidget()
VL=QVBoxLayout(window);HL=QHBoxLayout();VL.addLayout(HL)
GL=QGridLayout();HL.addLayout(GL)
GL.addWidget(QPushButton('R1C1'),0,0)
GL.addWidget(QPushButton('R1C2'),0,1)
GL.addWidget(QPushButton('R2C1'),1,0)
GL.addWidget(QPushButton('R1C1'),1,1)
HL.addStretch();VL.addStretch()
window.showMaximized()
app.exec_()

Upvotes: 4

Views: 5015

Answers (2)

Vali
Vali

Reputation: 11

I've solved this by using .setSpacing() and adding the below code:

MainLayout.addWidget(QLabel(''), MainLayout.rowCount(),0)
MainLayout.setRowStretch(MainLayout.rowCount(),1)
MainLayout.addWidget(QLabel(''),0,MainLayout.columnCount())
MainLayout.setColumnStretch(MainLayout.columnCount(),1)

.setSpacing() and .setContentMargins() will work beside this code, I don't know why, but it works very well.

Upvotes: 0

ekhumoro
ekhumoro

Reputation: 120578

The QGridLaout class doesn't have any simple convenience methods like QBoxLayout.addStretch() to do this. But the same effect can be achieved by adding some empty, stretchable rows/columns, like this:

GL.setRowStretch(GL.rowCount(), 1)
GL.setColumnStretch(GL.columnCount(), 1)

screenshot

Upvotes: 8

Related Questions