To achieve the desired behavior where the search bar and variables bar open to the right of the buttons, and the buttons move individually to accommodate the opening and closing of these bars without overlapping the right border of the results field, we'll refactor your existing PySide6 application.
The primary changes involve:
-
Using Layouts Instead of Absolute Positioning: This ensures that widgets adjust their positions dynamically based on the visibility of other widgets.
-
Organizing Buttons and Bars in Horizontal Layouts: This allows individual buttons to shift when their associated bars are toggled.
-
Implementing Smooth Transitions with Animations (Optional): For a polished user experience, animations can be added when toggling bars.
Below is the revised code with detailed explanations of the changes:
import math
import re
from typing import Any, Union, Callable
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QTextEdit, QScrollBar, QPushButton, QLabel, QFrame,
QGridLayout, QSizePolicy
)
from PySide6.QtGui import QFont, QIcon, Qt
from PySide6.QtCore import Qt, QSize, QRect, QPropertyAnimation, QEasingCurve
# ... [All your existing utility functions remain unchanged] ...
def evaluate_expression(expression: str, variables: dict, use_degrees: bool = False) -> Union[float, str]:
"""Evaluate math expression considering modes."""
assignment_match = re.match(r'^\s*([a-zA-Z_]\w*)\s*=\s*(.+)$', expression)
expression = preprocess_text_functions(expression)
safe_globals = get_safe_globals(use_degrees, variables)
if assignment_match:
var_name, var_expr = assignment_match.groups()
var_value = safe_evaluate(var_expr, safe_globals)
try:
if isinstance(var_value, str) and not var_value.startswith("Error"):
if '.' in var_value:
var_value_converted = float(var_value)
else:
var_value_converted = int(var_value)
variables[var_name] = var_value_converted
return f"{var_name} = {var_value_converted}"
else:
return var_value
except ValueError:
return f"Error: Cannot assign non-numeric value to variable '{var_name}'"
else:
error = validate_inverse_trig(expression, safe_globals)
if error:
return error
return safe_evaluate(expression, safe_globals)
class CalculatorGUI(QMainWindow):
"""PySide6-based calculator application."""
def __init__(self):
super().__init__()
self.use_degrees = False
self.variables = {}
self.history_entries = []
self.text_functions = ['capitalize', 'duplicates']
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;")
# Custom ScrollBar is already handled by setting parent, no need to assign separately
# self.scrollbar = QScrollBar(Qt.Vertical)
# self.history_text.setVerticalScrollBar(self.scrollbar)
# *** Rearranged Buttons: Search, Variables, Delete History ***
# Buttons Layout
self.buttons_layout = QHBoxLayout()
self.buttons_layout.setContentsMargins(0, 0, 0, 0)
self.buttons_layout.setSpacing(5)
self.buttons_layout.setAlignment(Qt.AlignRight)
# Search Button
self.search_button = QPushButton("🔍")
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)
# Variables Button
self.vars_button = QPushButton("🧮") # Using an abacus emoji as an example
self.vars_button.setFixedSize(24, 24)
self.vars_button.setToolTip("Show Variables")
self.vars_button.setStyleSheet("""
QPushButton {
border: none;
background-color: rgba(255, 255, 255, 200);
font-size: 14px;
border-radius: 12px;
}
QPushButton:hover {
background-color: rgba(0, 150, 136, 200);
color: white;
}
""")
self.vars_button.clicked.connect(self.toggle_vars_overlay)
# Delete History Button
self.delete_button = QPushButton("🗑️")
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)
# Add buttons to the buttons_layout
self.buttons_layout.addWidget(self.search_button)
self.buttons_layout.addWidget(self.vars_button)
self.buttons_layout.addWidget(self.delete_button)
# Variables Overlay
self.vars_overlay = QLineEdit()
self.vars_overlay.setReadOnly(True)
self.vars_overlay.setPlaceholderText("a = 1, b = 85, ...")
self.vars_overlay.setFixedHeight(24)
self.vars_overlay.setFixedWidth(200) # Adjust as needed
self.vars_overlay.setStyleSheet("""
QLineEdit {
border: 1px solid gray;
border-radius: 4px;
padding: 2px 4px;
background-color: white;
}
""")
self.vars_overlay.setVisible(False)
# Delete Variables Button within Variables Overlay
self.vars_delete_button = QPushButton("🗑️")
self.vars_delete_button.setFixedSize(24, 24)
self.vars_delete_button.setToolTip("Clear Variables")
self.vars_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.vars_delete_button.clicked.connect(self.clear_variables)
self.vars_delete_button.setVisible(False)
# Search Bar
self.search_bar = QLineEdit()
self.search_bar.setPlaceholderText("Search...")
self.search_bar.setFixedHeight(24)
self.search_bar.setFixedWidth(200) # Adjust as needed
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)
# Function Buttons
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()
layout.setSpacing(5)
categories = [("Functions", 3), ("Conversions", 2), ("Text", 2), ("Constants", 2), ("Settings", 1)]
starting_row = 0
for category, col_span in categories:
label = QLabel(category)
label.setFont(font)
label.setAlignment(Qt.AlignCenter)
layout.addWidget(label, starting_row, 0, 1, col_span)
buttons = self.function_buttons.get(category, [])
for i, func in enumerate(buttons):
button = QPushButton(func)
button.setFont(font)
button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
if 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, starting_row + 1, 0, 1, 1)
else:
is_text_func = func in self.text_functions
is_constant = category == "Constants"
button.clicked.connect(lambda _, f=func: self.insert_function(f, is_constant=is_constant, is_text_function=is_text_func))
row = starting_row + 1 + (i // col_span)
col = i % col_span
layout.addWidget(button, row, col)
starting_row += 1 + math.ceil(len(buttons) / 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)
# Scrollbar is handled internally by QTextEdit
main_layout.addLayout(history_layout)
main_layout.addWidget(self.function_frame)
# Overlay Layout for Buttons and Bars
overlay_layout = QHBoxLayout()
overlay_layout.setContentsMargins(0, 0, 0, 0)
overlay_layout.setSpacing(5)
overlay_layout.setAlignment(Qt.AlignRight)
# Add bars and buttons to overlay_layout
overlay_layout.addWidget(self.search_bar)
overlay_layout.addWidget(self.vars_overlay)
overlay_layout.addLayout(self.buttons_layout)
main_layout.addLayout(overlay_layout)
# Variables Overlay Delete Button Positioning
vars_delete_layout = QHBoxLayout()
vars_delete_layout.setContentsMargins(0, 0, 0, 0)
vars_delete_layout.setSpacing(0)
vars_delete_layout.addStretch()
vars_delete_layout.addWidget(self.vars_delete_button)
self.vars_overlay.setLayout(vars_delete_layout)
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:
new_text = f'{current_text[:cursor_position]}{function}() {current_text[cursor_position:]}'
new_cursor_position = cursor_position + len(function) + 1
else:
new_text = f"{current_text[:cursor_position]}{function}() {current_text[cursor_position:]}"
new_cursor_position = cursor_position + len(function) + 1
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 with animation."""
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.animate_visibility(self.search_bar, not is_visible)
self.refresh_history()
def toggle_vars_overlay(self) -> None:
"""Toggle the visibility of the variables overlay with animation."""
is_visible = self.vars_overlay.isVisible()
self.vars_overlay.setVisible(not is_visible)
self.animate_visibility(self.vars_overlay, not is_visible)
if not is_visible:
self.update_vars_overlay()
self.vars_delete_button.setVisible(True)
else:
self.vars_delete_button.setVisible(False)
self.refresh_history()
def animate_visibility(self, widget: QWidget, visible: bool) -> None:
"""Animate the showing and hiding of a widget."""
animation = QPropertyAnimation(widget, b"maximumWidth")
animation.setDuration(300)
if visible:
widget.setMaximumWidth(0)
animation.setStartValue(0)
animation.setEndValue(widget.width())
else:
animation.setStartValue(widget.width())
animation.setEndValue(0)
animation.setEasingCurve(QEasingCurve.InOutQuad)
animation.start()
# Keep reference to the animation to prevent garbage collection
widget.animation = animation
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 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 overlay buttons on showing the window."""
super().showEvent(event)
# No need for manual positioning with layouts
def clear_history(self) -> None:
"""Clear the history entries and update the display."""
self.history_entries.clear()
self.refresh_history()
def update_vars_overlay(self) -> None:
"""Update the variables overlay with current variables."""
if not self.variables:
self.vars_overlay.setText("No variables assigned.")
else:
vars_text = ", ".join(f"{var} = {value}" for var, value in self.variables.items())
self.vars_overlay.setText(vars_text)
def clear_variables(self) -> None:
"""Clear all variables and update the variables overlay."""
self.variables.clear()
self.update_vars_overlay()
self.vars_overlay.setVisible(False)
self.vars_delete_button.setVisible(False)
def main() -> None:
"""Start the calculator application."""
app = QApplication([])
calculator = CalculatorGUI()
calculator.show()
app.exec()
if __name__ == "__main__":
main()
Key Changes and Explanations:
-
Layout Refactoring:
- Overlay Layout: Introduced an
overlay_layout (QHBoxLayout) that contains the search_bar, vars_overlay, and the buttons_layout. This layout is aligned to the right (Qt.AlignRight), ensuring that the buttons and bars are positioned on the right side of the window.
- Buttons Layout: Created a separate
buttons_layout (QHBoxLayout) for the search_button, vars_button, and delete_button. This layout manages the buttons independently and ensures they are aligned horizontally.
-
Dynamic Widget Visibility and Size:
- Search Bar and Variables Overlay: Both widgets (
search_bar and vars_overlay) have fixed widths. When they are toggled, their visibility changes, and the layout automatically adjusts the positions of the buttons.
- Animations: Added a method
animate_visibility to handle smooth width transitions when showing or hiding the bars. This uses QPropertyAnimation to animate the maximumWidth property of the widgets.
-
Functions to Toggle Bars:
toggle_search and toggle_vars_overlay: These methods handle the visibility toggling of the search bar and variables overlay respectively. They call animate_visibility to perform the animation and adjust related widget states.
-
Variables Overlay Delete Button:
- The
vars_delete_button is placed inside the vars_overlay using an internal QHBoxLayout (vars_delete_layout). This ensures that the delete button aligns properly within the overlay.
-
Responsive Design:
- By using layouts (
QHBoxLayout and QVBoxLayout), the UI becomes more responsive to window resizing. The buttons and bars adjust their positions dynamically based on the window size and the visibility of other widgets.
-
Elimination of Absolute Positioning:
- Removed the
update_overlay_buttons_position method and all calls. Instead, the layout managers handle the positioning, making the UI more maintainable and flexible.
Additional Notes:
-
Fixed Widths: The search_bar and vars_overlay have fixed widths set (200 pixels in this example). You can adjust these values as needed.
-
Animations and Garbage Collection: To prevent the QPropertyAnimation objects from being garbage collected (which would stop the animation prematurely), we assign the animation to the widget (widget.animation = animation).
-
Layout Margins and Spacing: Adjusted the spacing and contentsMargins in layouts to ensure proper spacing between widgets. Feel free to tweak these values to fit your design preferences.
-
Easing Curves: The QEasingCurve.InOutQuad provides a smooth start and end to the animation. You can experiment with different easing curves to achieve the desired animation effect.
By implementing these changes, your calculator application will now have a responsive UI where the search bar and variables bar open and close gracefully, with their associated buttons moving individually to accommodate the space without overlapping other elements.