Move the search button to the right upper corner of the results field instead of the upper middle. Python 3.12 code: import math
import re
from typing import Any, Union, Callable
from math import ceil
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QTextEdit, QScrollBar, QPushButton, QLabel, QFrame,
QGridLayout
)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt, QSize
-- Utility Functions --
def convert_angle(func: Callable[[float], float], x: float, use_degrees: bool) -> float:
"""Convert angle based on degree mode."""
return func(math.radians(x) if use_degrees else x)
-- Conversions Category --
def kilograms_to_pounds(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text: str) -> str:
"""Remove duplicate words and empty lines from a string."""
words = ' '.join(line.strip() for line in text.splitlines() if line.strip()).split()
return ' '.join(dict.fromkeys(words))
def preprocess_text_functions(expression: str) -> str:
"""Preprocess text functions to ensure proper quoting of arguments."""
def add_quotes(match):
func, args = match.groups()
return f'{func}("{args}")' if func in ['capitalize', 'duplicates'] else match.group(0)
# Corrected regex pattern with only two capturing groups
return re.sub(r'\b(capitalize|duplicates)(([^)]+))', add_quotes, expression)
Assistant
def validate_inverse_trig(expression: str, safe_globals: dict) -> Union[str, None]:
"""Validate inputs for inverse trigonometric functions."""
for func, arg in re.findall(r"(\b\w+\b)(([^)]+))", expression):
if func in ["asin", "acos"]:
try:
value = eval(arg, {"builtins": None}, safe_globals)
if abs(value) > 1:
return f"Error: {func}(x) is undefined for |x| > 1"
except Exception as e:
return f"Error: {e}"
return None
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[str, Any]:
"""Safely evaluate the expression and format the result."""
try:
result = eval(expression, {"builtins": None}, safe_globals)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
if isinstance(result, (int, float)):
if use_e_notation:
# Format using scientific notation with up to 2 decimal places
result = f"{result:.2e}"
else:
# Standard formatting with rounding
result = round(result, 2)
return result
except Exception as e:
return f"Error: {e}"
To move the search button to the upper-right corner of the results field (i.e., the history_text area) instead of the upper middle, it's best to integrate the button into the layout rather than positioning it absolutely. This approach ensures that the button remains correctly positioned even when the window is resized or other elements are updated.
Here's how you can achieve this:
Remove Absolute Positioning:
Currently, the search_button is a child of history_text and is positioned using absolute coordinates. We'll remove this setup to allow layout managers to handle the positioning.
Use Layouts to Position the Button:
We'll create a container widget that holds both the history_text and the search_button.
Within this container, we'll use a QVBoxLayout for vertical arrangement and a QHBoxLayout to align the search_button to the right.
Adjust the Search Bar Positioning:
Similarly, ensure the search_bar is positioned appropriately within the layout.
Below is the modified code with detailed explanations for each change:
python
import math
import re
from typing import Any, Union, Callable
from math import ceil
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QTextEdit, QScrollBar, QPushButton, QLabel, QFrame,
QGridLayout
)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt, QSize
# -- [All your utility functions and processing functions remain unchanged] --
# -- GUI --
class CalculatorGUI(QMainWindow):
"""PySide6-based Calculator with Degrees/Radians toggle, Variables, History, and Search."""
def __init__(self):
super().__init__()
self.use_degrees = False
self.use_e_notation = False
self.variables = {} # Dictionary to store variables
self.history_entries = [] # List to store history entries
self.setup_window()
self.create_widgets()
self.layout_widgets()
def setup_window(self) -> None:
"""Configure the main application window."""
self.setWindowTitle("Calculator")
self.setGeometry(100, 100, 1280, 720)
def create_widgets(self) -> None:
"""Initialize all GUI components."""
font = QFont()
font.setPointSize(12)
font.setFamily('Literata')
# Entry field
self.entry = QLineEdit()
self.entry.setFont(font)
self.entry.returnPressed.connect(self.calculate)
self.entry.setPlaceholderText('Enter expression')
self.entry.setClearButtonEnabled(True)
# History text area
self.history_text = QTextEdit()
self.history_text.setFont(font)
self.history_text.setReadOnly(True)
self.history_text.setStyleSheet("") # Removed padding-right to eliminate vertical bar
# Scrollbar for history
self.scrollbar = QScrollBar(Qt.Vertical)
self.history_text.setVerticalScrollBar(self.scrollbar)
# Create search button (no parent)
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); /* Semi-transparent background */
font-size: 14px;
border-radius: 12px;
}
QPushButton:hover {
background-color: rgba(0, 120, 215, 200); /* Blue on hover */
color: white;
}
""")
self.search_button.clicked.connect(self.toggle_search)
# Search bar (hidden initially)
self.search_bar = QLineEdit()
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)
# 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 inserting functions into the entry."""
layout = QGridLayout()
# Define categories and their column spans
categories = [("Functions", 3), ("Conversions", 2), ("Text", 2), ("Constants", 2), ("Settings", 1)]
starting_col = 0
for category, col_span in categories:
# Add category label
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, False))
layout.addWidget(button, (i // 3) + 1, starting_col + (i % 3))
elif category == "Settings":
# Arrange Settings buttons vertically within a single column
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)
self.e_notation_button = QPushButton("E Notation: Off")
self.e_notation_button.setFont(font)
self.e_notation_button.clicked.connect(self.toggle_e_notation)
layout.addWidget(self.e_notation_button, 2, starting_col, 1, 1)
elif category == "Conversions":
for idx, func in enumerate(buttons):
if func == "lb":
display_text = "lb(kg)"
elif func == "kg":
display_text = "kg(lb)"
elif func == "K":
display_text = "K(°C)"
elif func == "C":
display_text = "°C(K)"
elif func == "F":
display_text = "F(°C)"
elif func == "CF":
display_text = "°C(F)"
else:
display_text = func
button = QPushButton(display_text)
button.setFont(font)
button.clicked.connect(lambda _, f=func: self.insert_function(f, False))
row = 1 + (idx // col_span)
col = starting_col + (idx % col_span)
layout.addWidget(button, row, col)
else:
num_buttons = len(buttons)
num_rows = ceil(num_buttons / col_span)
for idx, func in enumerate(buttons):
button_text = f"{func}"
button = QPushButton(button_text)
button.setFont(font)
button.clicked.connect(lambda _, f=func, c=(category == "Constants"): self.insert_function(f, c))
row = 1 + (idx // col_span)
col = starting_col + (idx % col_span)
layout.addWidget(button, row, col)
for extra in range(col_span * num_rows - num_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 within the window."""
central_widget = QWidget()
main_layout = QVBoxLayout()
# Add entry field
main_layout.addWidget(self.entry)
# Create a container for history_text and search controls
history_container = QWidget()
history_layout = QVBoxLayout()
history_layout.setContentsMargins(0, 0, 0, 0)
history_layout.setSpacing(5)
# Top bar layout for search button and search bar
top_bar = QHBoxLayout()
top_bar.setContentsMargins(0, 0, 0, 0)
top_bar.setSpacing(5)
top_bar.addStretch() # Push the search button to the right
top_bar.addWidget(self.search_button)
history_layout.addLayout(top_bar)
history_layout.addWidget(self.search_bar)
# Add history_text and scrollbar in a horizontal layout
history_scroll_layout = QHBoxLayout()
history_scroll_layout.setContentsMargins(0, 0, 0, 0)
history_scroll_layout.setSpacing(0)
history_scroll_layout.addWidget(self.history_text)
history_scroll_layout.addWidget(self.scrollbar)
history_layout.addLayout(history_scroll_layout)
history_container.setLayout(history_layout)
main_layout.addWidget(history_container)
# Add function buttons frame
main_layout.addWidget(self.function_frame)
central_widget.setLayout(main_layout)
self.setCentralWidget(central_widget)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
self.use_degrees = not self.use_degrees
self.mode_button.setText("Degrees" if self.use_degrees else "Radians")
def toggle_e_notation(self) -> None:
"""Toggle the E notation setting."""
self.use_e_notation = not self.use_e_notation
state = "On" if self.use_e_notation else "Off"
self.e_notation_button.setText(f"E Notation: {state}")
def insert_function(self, function: str, is_constant: bool = False) -> None:
"""Insert function or constant text into the expression 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)
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 the expression and update history."""
expression = self.entry.text().strip()
if expression:
result = evaluate_expression(
expression, self.variables, use_degrees=self.use_degrees, use_e_notation=self.use_e_notation
)
self.display_result(expression, result)
self.entry.clear()
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
mode = "D" if self.use_degrees else "R"
# Check if the expression is a variable assignment
if re.match(r'^\s*[a-zA-Z_]\w*\s*=\s*.+$', expression):
# For variable assignments, display only the result
history_entry = f"[{mode}] {result}"
else:
# For regular expressions, display expression and result
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()
)
# ------------------- Search Functionality ------------------- #
def toggle_search(self) -> None:
"""Show or hide the search bar."""
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("") # Clear previous search
self.refresh_history()
else:
self.search_bar.clear()
def filter_history(self, text: str) -> None:
"""Filter the history based on the search query."""
self.refresh_history(text)
def refresh_history(self, filter_text: str = "") -> None:
"""Refresh the history text field based on the filter."""
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 to reposition search bar."""
super().resizeEvent(event)
if self.search_bar.isVisible():
self.update_search_bar_size()
def update_search_bar_size(self) -> None:
"""Update the size of the search bar based on history_container's width."""
# Assuming search_bar should take up 25% of the history_container's width
history_container_width = self.history_text.width() + self.scrollbar.width()
new_width = int(history_container_width * 0.25)
self.search_bar.setFixedWidth(new_width)
def main() -> None:
"""Run the Calculator application."""
app = QApplication([])
calculator = CalculatorGUI()
calculator.show()
app.exec()
if __name__ == "__main__":
main()
Detailed Explanation of Changes:
Removing Absolute Positioning:
Removed Parent Association:
Previously, the search_button was a child of history_text, which caused it to overlay the history text.
Change:self.search_button = QPushButton("🔍")
Removed self.history_text as the parent.
Removed move Method:
The move method was used to position the button absolutely.
Change: Removed the self.search_button.move(...) line.
Creating a Container for History and Search:
New Container Widget:
Created a history_container widget to hold both the history_text and the search controls.
Layout Management:
Used a QVBoxLayout (history_layout) to arrange elements vertically.
Top Bar (QHBoxLayout):
Contains a stretchable space (addStretch()) to push the search_button to the right.
Added the search_button to the end of the QHBoxLayout to align it to the top-right.
Search Bar:
Placed below the search_button within the history_layout.
History and Scrollbar:
Added a QHBoxLayout (history_scroll_layout) for history_text and its scrollbar.
Advantage:
This ensures that the search_button remains at the top-right regardless of window resizing or other dynamic changes.
Adjusting the Search Bar:
Positioning:
The search_bar is placed directly below the search_button within the vertical layout.
Dynamic Sizing:
Final Touches:
Styling Consistency:
Ensured that the search_button and search_bar maintain their styles and tooltips.
Functionality Preservation:
All existing functionalities related to the search (like toggle_search and filter_history) remain intact and operate seamlessly within the new layout.
Conclusion
By restructuring the layout and removing absolute positioning, the search_button is now correctly positioned at the upper-right corner of the results field (history_text). This approach ensures that the UI is responsive, maintainable, and behaves as expected across different window sizes and user interactions.