Issue
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.
However, the QGridLayout
has the property that it automatically pads the spacing between widgets when the window is resized, i.e.
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
Solution
Add an expanding spacer to the last row/column of the grid-layout:
PyQt5/6:
vspacer = QtWidgets.QSpacerItem(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
layout.addItem(vspacer, last_row, 0, 1, -1)
hspacer = QtWidgets.QSpacerItem(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
layout.addItem(hspacer, 0, last_column, -1, 1)
PyQt4:
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)
Answered By - ekhumoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.