2

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_()
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Viswa
  • 134
  • 1
  • 13
  • It seems you already solved it, what's wrong with your version (besides its unnecessarily compressed and unreadable writing)? – musicamante Nov 08 '21 at 08:58

1 Answers1

4

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

ekhumoro
  • 115,249
  • 20
  • 229
  • 336