流式布局
流式布局,也叫做瀑布流布局,是网页中经常使用的一种页面布局方式,它的原理就是将高度固定,然后图片的宽度自适应,这样加载出来的图片看起来就像瀑布一样整齐的水流淌下来。
pyqt流式布局
那么在pyqt5中我们怎么使用流式布局呢?pyqt没有这个控件,需要我们自己去封装,下面是流式布局的封装代码。
```python
classFlowLayout(QLayout): def__init__(self, parent=None, margin=0, spacing=-1):
super(FlowLayout, self).__init__(parent)
if parent is not None: self.setContentsMargins(margin, margin, margin, margin)
self.setSpacing(spacing)
self.itemList = []
def__del__(self):
item = self.takeAt(0)
while item: item = self.takeAt(0)
defaddItem(self, item):
self.itemList.append(item)
defcount(self):
return len(self.itemList)
defitemAt(self, index):
if index >= 0 and index < len(self.itemList):
return self.itemList[index]
return None
deftakeAt(self, index):
if index >= 0 and index < len(self.itemList):
return self.itemList.pop(index)
return None
defexpandingDirections(self):
return Qt.Orientations(Qt.Orientation(0))
defhasHeightForWidth(self):
return True
defheightForWidth(self, width):
height = self.doLayout(QRect(0, 0, width, 0), True)
return height
defsetGeometry(self, rect):
super(FlowLayout, self).setGeometry(rect)
self.doLayout(rect, False)
defsizeHint(self):
return self.minimumSize()
defminimumSize(self):
size = QSize()
for item in self.itemList: size = size.expandedTo(item.minimumSize())
margin, _, _, _ = self.getContentsMargins()
size += QSize(2 * margin, 2 * margin)
return size
defdoLayout(self, rect, testOnly):
x = rect.x()
y = rect.y()
lineHeight = 0 for item in self.itemList: wid = item.widget()
spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
QSizePolicy.PushButton, Qt.Horizontal)
spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
QSizePolicy.PushButton, Qt.Vertical)
nextX = x + item.sizeHint().width() + spaceX
if nextX - spaceX > rect.right() and lineHeight > 0:
x = rect.x()
y = y + lineHeight + spaceY
nextX = x + item.sizeHint().width() + spaceX
lineHeight = 0 if not testOnly: item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
x = nextX
lineHeight = max(lineHeight, item.sizeHint().height())
return y + lineHeight - rect.y()
```