Keith L Keith L - 2 months ago 31
Python Question

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

I am building an application in

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

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

Grid (initial size)

However, the
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

class GridBlockTxtbx(QtGui.QWidget):

def __init__(self, blocks=5, spaces=5):
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!
# Function to load the widgets into the grid
GridBlockTxtbx._gen_block_txtbx_grid(layout, self.blocks,
# Set the 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


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)