import sys
import math
from typing import Callable

from qtpy import QtGui, QtCore
from qtpy.QtWidgets import QWidget, QToolButton, QApplication
# from PyQt5.Qt import *


class WrapPanel(QWidget):
    def __init__(self):
        super(WrapPanel, self).__init__()
        self.resize(500, 400)

        self.margin = 5  # 控件边距


    def resizeEvent(self, a0: QtGui.QResizeEvent) -> None:
        """
        根据调整后的窗体大小，重绘控件位置
        Args:
            a0: 窗口重绘事件

        Returns:
            无
        """
        rank = 0  # 第几个控件
        row = 0  # 行

        # 遍历每个子控件，检查控件大小，并进行位置重排
        for w in self.children():
            rank = rank + 1
            col = rank % (self.width() // (w.width() + self.margin))  # 当前控件所在列
            if col == 0:  # 控件如果是窗口宽度所能容纳的最后一个控件
                col = self.width() // (w.width() + self.margin)
            # 当前控件所在行
            if col == 1:
                row = row + 1  # 列重排为1时，表示增加了1行
                m = self.margin
            else:
                m = (self.margin + w.width()) * (col - 1)+self.margin

            if row == 1:
                n = self.margin
            else:
                n = (self.margin + w.height()) * (row - 1)+self.margin
            w.move(m, n)  # 重设控件位置
        self.update()

    def add_button(self,btn_name:str,btn_icon:str,btn_w:int,btn_h:int,btn_action:Callable) -> None:
        btn = QToolButton(self)
        btn.setText(btn_name)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(btn_icon), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        btn.setIcon(icon)
        btn.setIconSize(QtCore.QSize(50, 50))
        btn.setMaximumSize(btn_w, btn_h)
        btn.setMinimumSize(btn_w, btn_h)
        btn.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        btn.clicked.connect(btn_action)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = WrapPanel()
    win.show()
    sys.exit(app.exec_())
