GridLayout+ScrollArea widget position after size c

2019-06-05 04:45发布

问题:

I have a scrollArea with a gridlayout inside it, and i add QLabels to it with images. When the application starts it works fine and displays the labels correctly:

Note: i calculate how many labels fit on the current layout space.

If i maximize it works fine too:

But when i hit restore something weird happens:

You can see that only 6 labels are added (the same as in the first Screen shot) but here they are all positioned overlapping each other.

This is the initialization code for the ScrollArea and the Layout:

self.scrollArea = QtGui.QScrollArea(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth())
self.scrollArea.setSizePolicy(sizePolicy)
self.scrollArea.setAutoFillBackground(True)
self.scrollArea.setStyleSheet(_fromUtf8("border: 1px solid blue"))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.gridLayoutWidget = QtGui.QWidget()
self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 0, 667, 551))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.gridLayoutWidget.sizePolicy().hasHeightForWidth())
self.gridLayoutWidget.setSizePolicy(sizePolicy)
self.gridLayoutWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.gridLayoutWidget.setAutoFillBackground(True)
self.gridLayoutWidget.setStyleSheet(_fromUtf8("border: 1px solid red"))
self.gridLayoutWidget.setObjectName(_fromUtf8("gridLayoutWidget"))
self.scrollArea.setWidget(self.gridLayoutWidget)

回答1:

So thanks to #pyqt on freenode (shout out to Avaris) i now know what the problem is. It seems to be a bug in QGridLayout.

When we maximize the window QGridLayout ends up with 12 columns, when we do a restore even though every item is removed the layout still assumes 12 columns, so in picture 3 it is displaying 6 images but thinks it needs to display 12 so it just overlaps the other ones.