【问题标题】:How can the spacing between widgets in a QGridLayout remain fixed on window resize?QGridLayout 中小部件之间的间距如何在窗口调整大小时保持固定?
【发布时间】:2017-04-10 21:56:42
【问题描述】:

我正在PyQT4 中构建一个应用程序。这个应用程序的一个主要部分是维护一个小部件网格(从QLineEdit 小部件分类)。我将小部件组织成QGridLayout

当我运行窗口时,我得到了一个按照我想要的方式组织的网格,即

但是,QGridLayout 具有在调整窗口大小时自动填充小部件之间间距的属性,即

无论我如何调整窗口大小,我都希望网格在小部件之间具有相同的间距。我已经看过并且似乎无法找到如何做到这一点。我会想出一些可以固定间距的东西,但所有可能的发声功能都没有这种效果。

下面是一个代码sn-p,特别是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

【问题讨论】:

  • 如果你想要一个固定的间距,在调整大小时应该怎么做?小部件是否应该变大,或者网格应该获得更多的行和列,还是应该在网格之外有额外的空间?请指定所需的行为以使问题可以回答。
  • Ekhumoro 回答了,谢谢 :)
  • 确实如此。虽然他只是猜测,因为你没有具体说明你想要什么。这使得这个问题对其他人没有真正的用处
  • 感谢您的反馈和投票,Trilarion。 :)

标签: python python-3.x layout pyqt pyqt4


【解决方案1】:

在网格布局的最后一行/列中添加一个扩展间隔:

    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)

【讨论】:

  • 谢谢,这就是我要找的 :)
猜你喜欢
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
相关资源
最近更新 更多