我正在尝试使用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_())
答案 0 :(得分:2)
如果希望将sizeHint()
更改通知布局,则必须使用updateGeometry()
方法:
def mouseDoubleClickEvent(self, event):
self.w *= 2
self.h *= 2
self.updateGeometry() # <---
super(Rect, self).mouseDoubleClickEvent(event)
另一方面,如果您更改窗口的大小,则不会更改Rect的大小,因为QSpacerItem将占据它可能的所有大小。