Krita Source Code Documentation
Loading...
Searching...
No Matches
flow_layout.py
Go to the documentation of this file.
1# Copyright (C) 2013 Riverbank Computing Limited.
2# Copyright (C) 2022 The Qt Company Ltd.
3# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
4
5# FlowLayout class copied from https://doc.qt.io/qtforpython-6/examples/example_widgets_layouts_flowlayout.html
6
7try:
8 from PyQt6.QtCore import Qt, QMargins, QPoint, QRect, QSize
9 from PyQt6.QtWidgets import QLayout, QSizePolicy
10except:
11 from PyQt5.QtCore import Qt, QMargins, QPoint, QRect, QSize
12 from PyQt5.QtWidgets import QLayout, QSizePolicy
13
14class FlowLayout(QLayout):
15 def __init__(self, parent=None):
16 super().__init__(parent)
17
18 if parent is not None:
19 self.setContentsMargins(QMargins(0, 0, 0, 0))
20
21 self._item_list = []
22
23 def __del__(self):
24 item = self.takeAt(0)
25 while item:
26 item = self.takeAt(0)
27
28 def addItem(self, item):
29 self._item_list.append(item)
30
31 def count(self):
32 return len(self._item_list)
33
34 def itemAt(self, index):
35 if 0 <= index < len(self._item_list):
36 return self._item_list[index]
37
38 return None
39
40 def takeAt(self, index):
41 if 0 <= index < len(self._item_list):
42 return self._item_list.pop(index)
43
44 return None
45
47 return Qt.Orientation(0)
48
50 return True
51
52 def heightForWidth(self, width):
53 height = self._do_layout(QRect(0, 0, width, 0), True)
54 return height
55
56 def setGeometry(self, rect):
57 super(FlowLayout, self).setGeometry(rect)
58 self._do_layout(rect, False)
59
60 def sizeHint(self):
61 return self.minimumSize()
62
63 def minimumSize(self):
64 size = QSize()
65
66 for item in self._item_list:
67 size = size.expandedTo(item.minimumSize())
68
69 size += QSize(2 * self.contentsMargins().top(), 2 * self.contentsMargins().top())
70 return size
71
72 def _do_layout(self, rect, test_only):
73 x = rect.x()
74 y = rect.y()
75 line_height = 0
76 spacing = self.spacing()
77
78 for item in self._item_list:
79 style = item.widget().style()
80 layout_spacing_x = style.layoutSpacing(
81 QSizePolicy.ControlType.PushButton, QSizePolicy.ControlType.PushButton, Qt.Orientation.Horizontal
82 )
83 layout_spacing_y = style.layoutSpacing(
84 QSizePolicy.ControlType.PushButton, QSizePolicy.ControlType.PushButton, Qt.Orientation.Vertical
85 )
86 space_x = spacing + layout_spacing_x
87 space_y = spacing + layout_spacing_y
88 next_x = x + item.sizeHint().width() + space_x
89 if next_x - space_x > rect.right() and line_height > 0:
90 x = rect.x()
91 y = y + line_height + space_y
92 next_x = x + item.sizeHint().width() + space_x
93 line_height = 0
94
95 if not test_only:
96 item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
97
98 x = next_x
99 line_height = max(line_height, item.sizeHint().height())
100
101 return y + line_height - rect.y()