Modify the delete buttons (history and variables) so that they only activate after pressing on it for 3 seconds. Python code: 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
)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt
def convert_angle(func: Callable[[float], float], x: float, use_degrees: bool) -> float:
"""Convert angle based on mode (degrees/radians)."""
return func(math.radians(x)) if use_degrees else func(x)
def kilograms_to_pounds(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def capitalize_sentence(sentence: str) -> str:
"""Capitalize each word in a sentence."""
return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text: str) -> str:
"""Remove duplicate words from text."""
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 by ensuring arguments are quoted."""
def add_quotes(match):
func, args = match.groups()
args = args.strip()
if not (args.startswith('"') and args.endswith('"')) and not (args.startswith("'") and args.endswith("'")):
args = f'"{args}"'
return f'{func}({args})'
return re.sub(r'\b(capitalize|duplicates)\s*(\s*([^)]+)\s*)', add_quotes, expression)
def validate_inverse_trig(expression: str, safe_globals: dict) -> Union[str, None]:
"""Validate the domain of inverse trigonometric functions."""
for func, arg in re.findall(r'\b(asin|acos)\s*(\s*([^)]+)\s*)', expression):
try:
value = eval(arg, {"builtins": None}, safe_globals)
if abs(value) > 1:
return f"Error: {func}({arg}) is undefined for |{arg}| > 1"
except Exception as e:
return f"Error: {e}"
return None
Assistant
def safe_evaluate(expression: str, safe_globals: dict) -> Union[str, Any]:
"""Safely evaluate the mathematical expression."""
try:
result = eval(expression, {"builtins": None}, safe_globals)
if isinstance(result, (int, float)):
epsilon = 1e-10
if isinstance(result, float):
if math.isclose(result, 0.0, abs_tol=epsilon):
result = 0.0
abs_result = abs(result)
if (abs_result >= 1e9) or (abs_result != 0 and abs_result < 1e-6):
result = f"{result:.3e}"
else:
result = f"{result:.3f}"
else:
if len(str(abs(result))) > 9:
result = f"{result:.3e}"
else:
result = str(result)
return result
else:
return result
except Exception as e:
return f"Error: {e}"
if assignment_match:
var_name, var_expr = assignment_match.groups()
# Check if the variable name is reserved
if var_name in reserved_names:
return f"Error: '{var_name}' is a reserved name and cannot be used as a variable."
safe_globals = get_safe_globals(use_degrees, variables)
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}'"
def connect_signals(self) -> None:
"""Connect global signals."""
QApplication.instance().focusChanged.connect(self.on_focus_changed)
def toggle_mode(self) -> None:
"""Toggle between degrees and radians for trigonometric functions."""
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 the selected function into the entry field."""
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 the expression entered by the user."""
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:
"""Display the result in the 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 the visibility of the search bar."""
if self.search_bar.isVisible():
self.search_bar.setVisible(False)
else:
self.search_bar.setVisible(True)
self.search_bar.setFocus()
self.update_overlay_buttons_position()
def filter_history(self, text: str) -> None:
"""Filter the history based on search text."""
self.refresh_history(text)
def refresh_history(self, filter_text: str = "") -> None:
"""Refresh the history display, optionally filtering results."""
self.history_text.clear()
for entry in self.history_entries:
if filter_text.lower() in entry.lower():
self.history_text.append(entry)
def update_overlay_buttons_position(self) -> None:
"""Update the position of overlay buttons based on current window size."""
size = self.history_text.viewport().size()
def on_focus_changed(self, old: QWidget, new: QWidget) -> None:
"""Handle focus changes to hide overlays when necessary."""
if self.vars_overlay.isVisible() and new not in {self.vars_overlay, self.vars_delete_button, self.vars_button}:
self.vars_overlay.setVisible(False)
self.vars_delete_button.setVisible(False)
self.update_overlay_buttons_position()
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:
"""Handle the show event to position overlays correctly."""
super().showEvent(event)
self.update_overlay_buttons_position()
def clear_history(self) -> None:
"""Clear the calculation history."""
self.history_entries.clear()
self.refresh_history()
def toggle_vars_overlay(self) -> None:
"""Toggle the visibility of the variables overlay."""
if self.vars_overlay.isVisible():
self.vars_overlay.setVisible(False)
self.vars_delete_button.setVisible(False)
else:
self.update_vars_overlay()
self.vars_overlay.setVisible(True)
self.vars_delete_button.setVisible(True)
self.update_overlay_buttons_position()
def update_vars_overlay(self) -> None:
"""Update the text displayed in the variables overlay."""
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 main() -> None:
"""Main function to run the calculator application."""
app = QApplication([])
calculator = CalculatorGUI()
calculator.show()
app.exec()
if name == "main":
main()
To modify the delete buttons (self.delete_button and self.vars_delete_button) so that they activate only after being pressed and held for 3 seconds, you can implement a custom QPushButton that detects a long press. Below are the steps to achieve this:
Create a Custom LongPressButton Class:
Subclass QPushButton to create a LongPressButton that emits a custom signal (longPressed) when the button is held down for 3 seconds.
Replace Existing Delete Buttons with LongPressButton:
Use the newly created LongPressButton for both the history and variables delete buttons, and connect the longPressed signal to their respective handler methods (clear_history and clear_variables).
Provide Visual Feedback (Optional):
To enhance user experience, you can add visual feedback indicating that the button is being held.
Below is the complete updated code incorporating these 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
)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt, QTimer, Signal, QObject
# -------------------- Custom LongPressButton Class --------------------
class LongPressButton(QPushButton):
"""A QPushButton that emits a signal only if pressed and held for a specified duration."""
longPressed = Signal()
def __init__(self, text="", parent=None, hold_duration=3000):
"""
Initialize the button.
Args:
text (str): Button label.
parent (QWidget): Parent widget.
hold_duration (int): Duration in milliseconds to detect a long press.
"""
super().__init__(text, parent)
self.hold_duration = hold_duration # milliseconds
self.timer = QTimer(self)
self.timer.setSingleShot(True)
self.timer.timeout.connect(self.on_long_press)
self.pressed.connect(self.on_press)
self.released.connect(self.on_release)
self.is_long_press = False
def on_press(self):
"""Start the timer when the button is pressed."""
self.is_long_press = False
self.timer.start(self.hold_duration)
def on_release(self):
"""Stop the timer if the button is released before the hold duration."""
if self.timer.isActive():
self.timer.stop()
elif self.is_long_press:
# Already emitted in on_long_press
pass
else:
# Optional: Emit a regular clicked signal if needed
self.clicked.emit()
def on_long_press(self):
"""Handle the long press event."""
self.is_long_press = True
self.longPressed.emit()
# ------------------------ Existing Utility Functions ------------------------
# (Keep all your existing utility functions here)
# ... [Your utility functions as provided above] ...
# ---------------------------- CalculatorGUI Class ----------------------------
class CalculatorGUI(QMainWindow):
def __init__(self):
super().__init__()
self.use_degrees = True
self.variables = {}
self.history_entries = []
self.text_functions = ['capitalize', 'duplicates']
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.connect_signals()
# ... [Keep all existing methods up to create_widgets] ...
def create_widgets(self) -> None:
"""Create all widgets used in the application."""
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)
# Replace QPushButton with LongPressButton for 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(234, 235, 239, 255);
color: white;
}
""")
self.search_button.clicked.connect(self.toggle_search)
self.search_button.raise_()
# Replace delete_button with LongPressButton for clearing history
self.delete_button = LongPressButton("🗑️", self.history_text, hold_duration=3000)
self.delete_button.setFixedSize(24, 24)
self.delete_button.setToolTip("Clear History (Hold for 3 seconds)")
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(234, 235, 239, 255);
color: white;
}
""")
self.delete_button.longPressed.connect(self.clear_history)
self.delete_button.raise_()
# Replace vars_delete_button with LongPressButton for clearing variables
self.vars_button = QPushButton("🧮", self.history_text)
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(234, 235, 239, 255);
color: white;
}
""")
self.vars_button.clicked.connect(self.toggle_vars_overlay)
self.vars_button.raise_()
# vars_overlay and vars_delete_button remain mostly unchanged, except replacing vars_delete_button
self.vars_overlay = QLineEdit(self.history_text)
self.vars_overlay.setReadOnly(True)
self.vars_overlay.setPlaceholderText("a = 1, b = 85, ...")
self.vars_overlay.setFixedHeight(24)
self.vars_overlay.setFixedWidth(300)
self.vars_overlay.setStyleSheet("""
QLineEdit {
border: 1px solid gray;
border-radius: 4px;
padding: 2px 4px;
background-color: white;
}
""")
self.vars_overlay.setVisible(False)
# Replace vars_delete_button with LongPressButton
self.vars_delete_button = LongPressButton("🗑️", self.vars_overlay, hold_duration=3000)
self.vars_delete_button.setFixedSize(16, 16)
self.vars_delete_button.setToolTip("Clear Variables (Hold for 3 seconds)")
self.vars_delete_button.setStyleSheet("""
QPushButton {
border: none;
background-color: rgba(255, 255, 255, 200);
font-size: 10px;
border-radius: 8px;
}
QPushButton:hover {
background-color: rgba(234, 235, 239, 255);
color: white;
}
""")
self.vars_delete_button.longPressed.connect(self.clear_variables)
self.vars_delete_button.setVisible(False)
self.search_bar = QLineEdit(self.history_text)
self.search_bar.setPlaceholderText("Search...")
self.search_bar.setFixedHeight(24)
self.search_bar.setFixedWidth(300)
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)
# ... [Keep the rest of your existing methods unchanged] ...
# Optionally, you can add visual feedback for LongPressButton
# For example, changing the button color while holding down
# Here's how you can modify the LongPressButton if desired
# ---------------------------- Main Function ----------------------------
def main() -> None:
"""Main function to run the calculator application."""
app = QApplication([])
calculator = CalculatorGUI()
calculator.show()
app.exec()
if __name__ == "__main__":
main()
Explanation of Changes
Custom LongPressButton Class:
Purpose: Detects a long press (holding the button for a specified duration) and emits a longPressed signal.
Key Components:
longPressed Signal: Custom signal emitted after the hold duration.
hold_duration: Duration in milliseconds to detect a long press (set to 3000 ms for 3 seconds).
QTimer: Timer that starts on button press and triggers longPressed if the button is held long enough.
Event Handlers:
on_press: Starts the timer when the button is pressed.
on_release: Stops the timer if the button is released before the hold duration; otherwise, does nothing if longPressed has already been emitted.
on_long_press: Emits the longPressed signal when the timer completes without interruption.
Replacing Delete Buttons:
History Delete Button (self.delete_button):
Changed from QPushButton to LongPressButton.
Connected the longPressed signal to the clear_history method.
Updated the tooltip to indicate that a 3-second hold is required.
Connected the longPressed signal to the clear_variables method.
Updated the tooltip similarly.
Optional Visual Feedback:
You can enhance user experience by providing visual feedback (e.g., changing the button’s color while being held) by modifying the LongPressButton class further. This can involve connecting to the pressed and timeout events to adjust styles dynamically.
Handling Regular Clicks (Optional):
Testing the Changes
Run the Application:
Execute your script to launch the calculator application.
Clear History:
Action: Press and hold the history delete button (🗑️) for 3 seconds.
Expected Result: The history should be cleared only after holding the button for the specified duration.
Clear Variables:
Action: Similarly, press and hold the variables delete button (🗑️) for 3 seconds.
Expected Result: All assigned variables should be cleared after the hold.
Short Press:
Action: Click the delete buttons normally (without holding).
Expected Result: Since the LongPressButton emits a regular clicked signal upon a short press, it will perform the default action (if connected). In the provided implementation, short presses will still trigger the clicked signal unless you modify the on_release method to ignore them. If you want to prevent any action on short presses, you can remove or comment out the self.clicked.emit() line in the on_release method.
Additional Enhancements
Visual Indicator:
Add a progress indicator or change the button's appearance while it's being held down to provide feedback to the user.
Adjustable Hold Duration:
Modify the hold_duration parameter when creating LongPressButton instances if you wish to use different hold durations for different buttons.
Prevent Accidental Clears:
Ensure that the user is aware of the long-press requirement, possibly through user interface hints or instructions.
By implementing the LongPressButton as shown, you enhance the application's usability and prevent accidental deletions by requiring users to deliberately hold down the delete buttons for 3 seconds.
If you want the button to also handle regular clicks differently from long presses, you can emit a different signal or handle it within the on_release method. In the provided code, if the button is released before the hold duration, it emits the regular clicked signal, which you can connect to another handler if desired.