48 lines
1.6 KiB
Python
48 lines
1.6 KiB
Python
import re
|
|
|
|
from PyQt6.QtGui import QColor
|
|
from PyQt6.QtWidgets import QWidget, QHBoxLayout, QPushButton, QColorDialog, QSizePolicy
|
|
|
|
|
|
class ColorButton(QPushButton):
|
|
def __init__(self, color: str):
|
|
super(QPushButton, self).__init__()
|
|
self.color = color
|
|
self.setStyleSheet("background-color: #%s" % color)
|
|
self.pressed.connect(self._update_color)
|
|
self.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
|
|
|
|
def set_color(self, color: str):
|
|
if self._is_hex_color(color):
|
|
self.setStyleSheet("background-color: #%s" % color)
|
|
self.setText(color)
|
|
self.color = color
|
|
else:
|
|
self.setStyleSheet("background-color: none")
|
|
self.setText(self.tr("not set"))
|
|
self.color = "None"
|
|
|
|
def _update_color(self):
|
|
new_color = QColorDialog.getColor(self._to_qcolor(self.color))
|
|
if new_color.isValid():
|
|
color = self._to_hex(new_color)
|
|
self.set_color(color)
|
|
|
|
@staticmethod
|
|
def _is_hex_color(color: str):
|
|
return re.match("[0-9a-f]{6}", color, flags=re.IGNORECASE)
|
|
|
|
def _to_qcolor(self, color: str):
|
|
if self._is_hex_color(color):
|
|
red = int(color[0:2], 16)
|
|
green = int(color[2:4], 16)
|
|
blue = int(color[4:6], 16)
|
|
return QColor(red, green, blue)
|
|
return QColor(255, 255, 255)
|
|
|
|
def _to_hex(self, color: QColor) -> str:
|
|
red = "{0:0{1}x}".format(color.red(), 2)
|
|
green = "{0:0{1}x}".format(color.green(), 2)
|
|
blue = "{0:0{1}x}".format(color.blue(), 2)
|
|
return red + green + blue
|