调整内容大小时 QGridLayout 不更新?

QGridLayout doesn't update when contents is resized?

我正在尝试使用 QGridLayout 来容纳可调整大小的小部件,但是当我调整它们大小时它不起作用,QGridLayout 单元格保持相同大小...

这是一个让我感到困惑的场景的最小工作示例。双击红色方块应该会增加它们的大小:

from PyQt5 import QtGui, QtWidgets
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import QSizePolicy
import sys

class Rect(QtWidgets.QFrame):
    def __init__(self, width, height):
        super().__init__()
        self.w = width
        self.h = height
        self.setStyleSheet("background-color: red")

    def mouseDoubleClickEvent(self, a0: QtGui.QMouseEvent):
        self.w *= 2
        self.h *= 2

        print(self.sizeHint())

    def sizeHint(self):
        return QSize(self.w,self.h)

    def minimumSizeHint(self):
        return self.sizeHint()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    gridLayout = QtWidgets.QGridLayout()

    gridLayout.addWidget(Rect(100,100), 0, 0, 1, 1)
    gridLayout.addWidget(Rect(100,100), 1, 1, 1, 1)
    gridLayout.addItem(QtWidgets.QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding), 2, 2, 1, 1)

    container = QtWidgets.QFrame()
    container.setLayout(gridLayout)

    container.resize(600,600)
    container.show()
    sys.exit(app.exec_())

如果您希望将 sizeHint() 更改通知给布局,您必须使用 updateGeometry() 方法:

def mouseDoubleClickEvent(self, event):
    self.w *= 2
    self.h *= 2
    self.updateGeometry() # <---
    super(Rect, self).mouseDoubleClickEvent(event)

另一方面,如果您更改 window 的大小,它不会更改 Rect 的大小,因为 QSpacerItem 将占据它可以占据的所有大小。