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_()
Required Result:
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_()
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)