omega/app/ui/current_word.py

55 lines
1.6 KiB
Python

from PySide6.QtWidgets import QGraphicsRectItem, QGraphicsSimpleTextItem
from PySide6.QtGui import QFont, QFontMetricsF, QColor, QBrush
BACKGROUND_COLOR = QColor("white")
TEXT_SCALE_FACTOR = 0.4 # 40% of the width or height
Z_INDEX = 10
class CurrentWordBox(QGraphicsRectItem):
def __init__(self):
super().__init__()
self.word = ""
self.text = QGraphicsSimpleTextItem("", self)
self.text.setFlag(QGraphicsSimpleTextItem.ItemIgnoresTransformations, True)
self.setBrush(QBrush(BACKGROUND_COLOR))
self.setZValue(Z_INDEX)
self.width = 0
self.height = 0
def set_geometry(self, x: float, y: float, width: float, height: float):
self.width = width
self.height = height
self.setRect(0, 0, width, height)
self.setPos(x, y)
self.update_label_font()
def update_word(self, next_char: str):
self.word += next_char
self.text.setText(self.word)
self.update_label_font()
def clear(self):
self.word = ""
self.text.setText("")
self.update_label_font()
def update_label_font(self):
min_dimension = min(self.width, self.height)
font_size = min_dimension * TEXT_SCALE_FACTOR
font = QFont()
font.setPointSizeF(font_size)
self.text.setFont(font)
metrics = QFontMetricsF(font)
text_rect = metrics.boundingRect(self.word)
text_x = (self.width - text_rect.width()) / 2
text_y = (self.height - text_rect.height()) / 2
self.text.setPos(text_x, text_y)