def __init__(self):
super().__init__()
self.use_degrees = False
self.variables = {}
self.history_entries = []
self.text_functions = ['capitalize', 'duplicates'] # Define text functions
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.connect_signals()
def setup_window(self) -> None:
"""Set main window properties."""
self.setWindowTitle("Calculator")
self.setGeometry(100, 100, 1280, 720)
def create_widgets(self) -> None:
"""Initialize GUI components."""
font = QFont()
font.setPointSize(12)
font.setFamily('Literata')
self.entry = QLineEdit()
self.entry.setFont(font)
self.entry.setPlaceholderText('Enter expression')
self.entry.setClearButtonEnabled(True)
self.entry.returnPressed.connect(self.calculate)
self.history_text = QTextEdit()
self.history_text.setFont(font)
self.history_text.setReadOnly(True)
self.history_text.setStyleSheet("position: relative;")
self.scrollbar = QScrollBar(Qt.Vertical)
self.history_text.setVerticalScrollBar(self.scrollbar)
# Create the search button
self.search_button = QPushButton("🔍", self.history_text)
self.search_button.setFixedSize(24, 24)
self.search_button.setToolTip("Search History")
self.search_button.setStyleSheet("""
QPushButton {
border: none;
background-color: rgba(255, 255, 255, 200);
font-size: 14px;
border-radius: 12px;
}
QPushButton:hover {
background-color: rgba(0, 120, 215, 200);
color: white;
}
""")
self.search_button.clicked.connect(self.toggle_search)
self.search_button.raise_()
# Create the delete button
self.delete_button = QPushButton("🗑️", self.history_text)
self.delete_button.setFixedSize(24, 24)
self.delete_button.setToolTip("Clear History")
self.delete_button.setStyleSheet("""
QPushButton {
border: none;
background-color: rgba(255, 255, 255, 200);
font-size: 14px;
border-radius: 12px;
}
QPushButton:hover {
background-color: rgba(255, 0, 0, 200);
color: white;
}
""")
self.delete_button.clicked.connect(self.clear_history)
self.delete_button.raise_()
# Create the search bar
self.search_bar = QLineEdit(self.history_text)
self.search_bar.setPlaceholderText("Search...")
self.search_bar.setFixedHeight(24)
self.search_bar.setVisible(False)
self.search_bar.setStyleSheet("""
QLineEdit {
border: 1px solid gray;
border-radius: 4px;
padding: 2px 4px;
background-color: white;
}
""")
self.search_bar.textChanged.connect(self.filter_history)
self.search_bar.setClearButtonEnabled(True)
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg", "K", "C", "F", "CF"],
"Text": ["capitalize", "duplicates"],
"Constants": ["pi", "e"],
"Settings": []
}
self.function_frame = QFrame()
self.create_function_buttons(font)
def create_function_buttons(self, font: QFont) -> None:
"""Create buttons for calculator functions."""
layout = QGridLayout()
categories = [("Functions", 3), ("Conversions", 2), ("Text", 2), ("Constants", 2), ("Settings", 1)]
starting_col = 0
for category, col_span in categories:
label = QLabel(category)
label.setFont(font)
layout.addWidget(label, 0, starting_col, 1, col_span, Qt.AlignCenter)
buttons = self.function_buttons.get(category, [])
if category == "Functions":
for i, func in enumerate(buttons):
button = QPushButton(func)
button.setFont(font)
button.clicked.connect(lambda _, f=func: self.insert_function(f, is_text_function=(f in self.text_functions)))
layout.addWidget(button, (i // 3) + 1, starting_col + (i % 3))
elif category == "Settings":
self.mode_button = QPushButton("Radians")
self.mode_button.setFont(font)
self.mode_button.clicked.connect(self.toggle_mode)
layout.addWidget(self.mode_button, 1, starting_col, 1, 1)
elif category == "Conversions":
for idx, func in enumerate(buttons):
display_text = {
"lb": "lb(kg)", "kg": "kg(lb)", "K": "K(°C)",
"C": "°C(K)", "F": "F(°C)", "CF": "°C(F)"
}.get(func, func)
button = QPushButton(display_text)
button.setFont(font)
button.clicked.connect(lambda _, f=func: self.insert_function(f, is_text_function=False))
row, col = 1 + idx // 2, starting_col + idx % 2
layout.addWidget(button, row, col)
elif category == "Text":
for idx, func in enumerate(buttons):
button = QPushButton(func)
button.setFont(font)
# Connect text functions with is_text_function=True
button.clicked.connect(lambda _, f=func: self.insert_function(f, is_text_function=True))
row, col = 1 + idx // col_span, starting_col + idx % col_span
layout.addWidget(button, row, col)
elif category == "Constants":
for idx, func in enumerate(buttons):
button = QPushButton(func)
button.setFont(font)
# Constants can be treated as variables/constants
button.clicked.connect(lambda _, f=func: self.insert_function(f, is_constant=True))
row, col = 1 + idx // col_span, starting_col + idx % col_span
layout.addWidget(button, row, col)
# Fill the remaining grid cells with empty labels to maintain layout
for extra in range(col_span * math.ceil(len(buttons)/col_span) - len(buttons)):
layout.addWidget(QLabel(""), 1 + extra // col_span, starting_col + extra % col_span)
starting_col += col_span
self.function_frame.setLayout(layout)
def layout_widgets(self) -> None:
"""Arrange widgets in the main window."""
central_widget = QWidget()
main_layout = QVBoxLayout()
main_layout.addWidget(self.entry)
history_layout = QHBoxLayout()
history_layout.addWidget(self.history_text)
history_layout.addWidget(self.scrollbar)
main_layout.addLayout(history_layout)
main_layout.addWidget(self.function_frame)
central_widget.setLayout(main_layout)
self.setCentralWidget(central_widget)
def connect_signals(self) -> None:
"""Connect widget signals."""
QApplication.instance().focusChanged.connect(self.on_focus_changed)
def toggle_mode(self) -> None:
"""Toggle between degrees and radians."""
self.use_degrees = not self.use_degrees
self.mode_button.setText("Degrees" if self.use_degrees else "Radians")
def insert_function(self, function: str, is_constant: bool = False, is_text_function: bool = False) -> None:
"""Insert function or constant in entry."""
current_text = self.entry.text()
cursor_position = self.entry.cursorPosition()
if is_constant:
new_text = f"{current_text[:cursor_position]}{function} "
new_cursor_position = cursor_position + len(function) + 1
elif is_text_function and function in self.text_functions:
# Insert 'function("") ' and place the cursor inside the quotes
new_text = f'{current_text[:cursor_position]}{function}("") {current_text[cursor_position:]}'
new_cursor_position = cursor_position + len(function) + 1 # Position cursor inside quotes
else:
# Insert 'function() ' and place the cursor inside the parentheses
new_text = f"{current_text[:cursor_position]}{function}() {current_text[cursor_position:]}"
new_cursor_position = cursor_position + len(function) + 1 # Position cursor inside '('
self.entry.setText(new_text)
self.entry.setCursorPosition(new_cursor_position)
self.entry.setFocus()
def calculate(self) -> None:
"""Evaluate entered expression."""
expression = self.entry.text().strip()
if expression:
result = evaluate_expression(
expression, self.variables, use_degrees=self.use_degrees
)
self.display_result(expression, result)
self.entry.clear()
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Show result in history."""
mode = "D" if self.use_degrees else "R"
if re.match(r'^\s*[a-zA-Z_]\w*\s*=\s*.+$', expression):
history_entry = f"[{mode}] {result}"
else:
history_entry = f"[{mode}] {expression} = {result}"
self.history_entries.append(history_entry)
self.refresh_history()
self.history_text.verticalScrollBar().setValue(
self.history_text.verticalScrollBar().maximum()
)
def toggle_search(self) -> None:
"""Toggle search bar visibility."""
is_visible = self.search_bar.isVisible()
self.search_bar.setVisible(not is_visible)
if not is_visible:
self.search_bar.setFocus()
self.search_bar.setText("")
else:
self.search_bar.clear()
self.update_overlay_buttons_position()
self.refresh_history()
def filter_history(self, text: str) -> None:
"""Filter history based on search input."""
self.refresh_history(text)
def refresh_history(self, filter_text: str = "") -> None:
"""Refresh history view with optional filtering."""
self.history_text.clear()
for entry in self.history_entries:
if filter_text.lower() in entry.lower():
self.history_text.append(entry)
def resizeEvent(self, event) -> None:
"""Handle window resize events."""
super().resizeEvent(event)
self.update_overlay_buttons_position()
def update_overlay_buttons_position(self) -> None:
"""Reposition search and delete buttons over the history_text widget."""
history_rect = self.history_text.viewport().rect()
# Map viewport coordinates to the history_text widget
size = self.history_text.viewport().size()
# Constants for margins
margin_right = 5
margin_top = 5
margin_bottom = 5
spacing = 5
# Position the search button at top-right
self.search_button.move(
size.width() - self.search_button.width() - margin_right,
margin_top
)
# Position the delete button at bottom-right
self.delete_button.move(
size.width() - self.delete_button.width() - margin_right,
size.height() - self.delete_button.height() - margin_bottom
)
# Position the search bar if visible
if self.search_bar.isVisible():
search_bar_width = int(size.width() * 0.25)
if search_bar_width + self.search_button.width() + spacing + margin_right > size.width():
search_bar_width = size.width() - self.search_button.width() - spacing - margin_right
self.search_bar.setFixedWidth(search_bar_width)
self.search_bar.move(
self.search_button.x() - search_bar_width - spacing,
margin_top
)
def on_focus_changed(self, old: QWidget, new: QWidget) -> None:
"""Auto-hide search if focus is lost."""
if self.search_bar.isVisible() and not self.search_bar.text().strip() and new != self.search_bar:
self.toggle_search()
def showEvent(self, event) -> None:
"""Position search and delete buttons on showing the window."""
super().showEvent(event)
self.update_overlay_buttons_position()
def clear_history(self) -> None:
"""Clear the history entries and update the display."""
self.history_entries.clear()
self.refresh_history()