from PySide6.QtWidgets import ( QGraphicsRectItem, QGraphicsSimpleTextItem, QGraphicsItem ) from PySide6.QtGui import QBrush, QColor, QFont, QFontMetricsF class KeyItem(QGraphicsRectItem): def __init__(self, label): super().__init__() self.label = label self.text = QGraphicsSimpleTextItem(label, self) self.text.setFlag(QGraphicsItem.ItemIgnoresTransformations, True) self.setBrush(QBrush(QColor("lightgray"))) self.scale_factor = 1.0 self.width = 0 self.height = 0 def set_geometry(self, x, y, width, height): self.width = width self.height = height self.setRect(0, 0, width, height) self.setPos(x, y) self.setTransformOriginPoint(width / 2, height / 2) self.update_label_font() def update_label_font(self): # Dynamically size font font_size = min(self.width, self.height) * 0.4 font = QFont() font.setPointSizeF(font_size) self.text.setFont(font) # Use font metrics for accurate bounding metrics = QFontMetricsF(font) text_rect = metrics.boundingRect(self.label) text_x = (self.width - text_rect.width()) / 2 text_y = (self.height - text_rect.height()) / 2 # + metrics.ascent() - text_rect.height() self.text.setPos(text_x, text_y) def set_scale_factor(self, scale): self.scale_factor = scale self.setZValue(scale) self.setScale(scale) def mousePressEvent(self, q_mouse_event): print(self.label, "was clicked")