From 7ea671e7b070cb74bf67f5be64a2608959b13a82 Mon Sep 17 00:00:00 2001 From: WorldTeacher <41587052+WorldTeacher@users.noreply.github.com> Date: Wed, 17 Jul 2024 14:09:11 +0200 Subject: [PATCH] add icon, implement color change and overwrite --- src/utils/icon.py | 76 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/utils/icon.py diff --git a/src/utils/icon.py b/src/utils/icon.py new file mode 100644 index 0000000..c75dd97 --- /dev/null +++ b/src/utils/icon.py @@ -0,0 +1,76 @@ +from omegaconf import OmegaConf +from PyQt6 import QtGui +import re + +config = OmegaConf.load("icons/icons.yaml") + +path = "icons/" + + +class Icon: + def __init__(self, icon_type, widget=None): + self.icon = QtGui.QIcon() + self.icon_path = path + config["icons"][icon_type] + self.add_icon(self.icon_path) + if widget is not None: + widget.setIcon(self.icon) + + def add_icon(self, icon_path): + icon = self.changeColor(icon_path) + + # use icon bytes to create a pixmap + pixmap = QtGui.QPixmap() + pixmap.loadFromData(icon) + + self.icon.addPixmap( + pixmap, + QtGui.QIcon.Mode.Normal, + QtGui.QIcon.State.Off, + ) + + def overwriteColor(self, color): + # take the icon, read it as bytes and change the color in fill + icon = self.changeColor(self.icon_path) + cicon = str(icon) + fill = re.search(r"fill=\"(.*?)\"", cicon).group(1) + stroke = re.search(r"stroke=\"(.*?)\"", cicon) + if stroke: + stroke = stroke.group(1) + + if fill and stroke: + # replace stroke + newicon = icon.replace(stroke.encode(), color.encode()) + else: + newicon = icon.replace(fill.encode(), color.encode()) + + pixmap = QtGui.QPixmap() + pixmap.loadFromData(newicon) + + self.icon.addPixmap( + pixmap, + QtGui.QIcon.Mode.Normal, + QtGui.QIcon.State.Off, + ) + return self.icon + + @staticmethod + def changeColor(icon_path) -> bytes: + """change the color of the svg icon to the color set in the config file + + Args: + icon_path (str): the path to the icon, usually icons/[name].svg + + Returns: + icon: a byte representation of the icon with the new color + """ + color = config.color + with open(icon_path, "rb") as file: + icon = file.read() + cicon = str(icon) + fill = re.search(r"fill=\"(.*?)\"", cicon).group(1) + icon = icon.replace(fill.encode(), config.color.encode()) + return icon + + +if __name__ == "__main__": + print("This is a module and can not be executed directly.")