Keith L Keith L - 14 days ago 10
Python Question

How can the spacing between widgets in a QGridLayout remain fixed on window resize?

I am building an application in

PyQT4
. A principle part of this app will be to maintain a grid of widgets (sub classed from
QLineEdit
widgets). I am organizing the widgets into a
QGridLayout
.

When I run the window, I get a grid organized just how I want, i.e.

Grid (initial size)

However, the
QGridLayout
has the property that it automatically pads the spacing between widgets when the window is resized, i.e.

Grid (expanded size)

I would love for the grid to have the same spacing between widgets, no matter how I resize the window. I have looked and cannot seem to find how to accomplish this. I would have imagined something that fixes the spacing, but none of the likely sounding functions have this effect.

Here is a code snippet below, specifically just the part with the
QGridLayout
.

class GridBlockTxtbx(QtGui.QWidget):

def __init__(self, blocks=5, spaces=5):
QtGui.QWidget.__init__(self)
self.dctn_txtbx = {}
self.blocks = blocks
self.spaces = spaces

# Create layout
layout = QtGui.QGridLayout()
# Set initial spacing between widgets to 2 pixels...
# I want this to be fixed on window resize!
layout.setSpacing(2)
# Function to load the widgets into the grid
GridBlockTxtbx._gen_block_txtbx_grid(layout, self.blocks,
self.spaces,
self.dctn_txtbx)
# Set the layout
self.setLayout(layout)

def _gen_block_txtbx_grid(layout, rows, cols, dctn):
for i in range(rows):
for j in range(cols):
blk = GridBlockTxtbx._gen_block_txtbx(idx=(i, j))
layout.addWidget(blk, i, j)
dctn[i, j] = blk

Answer

Add an expanding spacer to the last row/column of the grid-layout:

    vspacer = QtGui.QSpacerItem(
        QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
    layout.addItem(vspacer, last_row, 0, 1, -1)

    hspacer = QtGui.QSpacerItem(
        QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
    layout.addItem(hspacer, 0, last_column, -1, 1)