To add a small delete (clear) symbol in the right corner of the execution field (QLineEdit) that clears all text when clicked, you can utilize the built-in functionality of QLineEdit. PySide6 provides a straightforward way to enable a clear button within the QLineEdit widget. Additionally, if you prefer a custom delete icon, you can add a QAction with your desired icon.
Below are two approaches:
- Using the Built-in Clear Button
- Adding a Custom Clear Button
1. Using the Built-in Clear Button
PySide6's QLineEdit has a built-in method called setClearButtonEnabled which, when set to True, displays a clear button (typically an "X") on the right side of the input field. This button automatically clears the text when clicked.
Steps:
-
Enable the Clear Button:
Add the setClearButtonEnabled(True) method to your QLineEdit instance.
-
Optional Styling:
You can customize the appearance of the clear button using Qt Style Sheets if needed.
Implementation:
Modify the create_widgets method in your CalculatorGUI class as follows:
def create_widgets(self) -> None:
"""Initialize all GUI components."""
font = QFont()
font.setPointSize(12)
font.setFamily('Literata')
self.entry = QLineEdit()
self.entry.setFont(font)
self.entry.returnPressed.connect(self.calculate)
self.entry.setPlaceholderText('Enter expression')
# Enable the built-in clear button
self.entry.setClearButtonEnabled(True)
self.history_text = QTextEdit()
self.history_text.setFont(font)
self.history_text.setReadOnly(True)
self.scrollbar = QScrollBar(Qt.Vertical)
self.history_text.setVerticalScrollBar(self.scrollbar)
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"]
}
self.function_frame = QFrame()
self.create_function_buttons(font)
Result:
A small clear ("X") button will appear on the right side of the execution field (self.entry). Clicking this button will clear all text within the field.
2. Adding a Custom Clear Button
If you prefer to use a custom delete icon or need more control over the button's appearance and behavior, you can add a QAction with a custom icon to the QLineEdit.
Steps:
-
Create a Custom Action:
- Load an icon for the delete button.
- Create a
QAction with the icon.
-
Add the Action to QLineEdit:
- Use
addAction to place the action on the trailing (right) side.
-
Connect the Action:
- Link the action’s
triggered signal to a slot that clears the text.
Implementation:
First, ensure you have an appropriate icon for the delete button. For this example, we'll use a simple "delete" icon. You can use any icon file you prefer.
Assuming you have an icon named delete_icon.png in the same directory as your script:
from PySide6.QtGui import QIcon, QAction
import os
Modify the create_widgets method as follows:
def create_widgets(self) -> None:
"""Initialize all GUI components."""
font = QFont()
font.setPointSize(12)
font.setFamily('Literata')
self.entry = QLineEdit()
self.entry.setFont(font)
self.entry.returnPressed.connect(self.calculate)
self.entry.setPlaceholderText('Enter expression')
# Option 2: Add a custom clear button
delete_icon_path = os.path.join(os.path.dirname(__file__), "delete_icon.png")
if os.path.exists(delete_icon_path):
clear_action = QAction(QIcon(delete_icon_path), "Clear", self)
clear_action.triggered.connect(self.entry.clear)
# Add the action to the line edit on the trailing (right) side
self.entry.addAction(clear_action, QLineEdit.ActionPosition.TrailingPosition)
else:
print("Delete icon not found. Please ensure 'delete_icon.png' is in the script directory.")
self.history_text = QTextEdit()
self.history_text.setFont(font)
self.history_text.setReadOnly(True)
self.scrollbar = QScrollBar(Qt.Vertical)
self.history_text.setVerticalScrollBar(self.scrollbar)
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"]
}
self.function_frame = QFrame()
self.create_function_buttons(font)
Notes:
-
Icon File: Ensure that the delete_icon.png file exists in the same directory as your script. Replace "delete_icon.png" with the path to your desired icon if it's located elsewhere.
-
Error Handling: The code checks if the icon file exists. If not, it prints a message. You can handle this scenario as needed, possibly by falling back to the built-in clear button.
-
Customization: You can adjust the icon size and other properties using Qt Style Sheets or additional code as required.
Result:
A custom clear button with your specified icon will appear on the right side of the execution field (self.entry). Clicking this button will clear all text within the field.
Complete Modified Code
Below is the complete modified code incorporating the built-in clear button method. If you choose to implement the custom clear button, ensure you follow the steps in Option 2 and include the appropriate icon file.
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
# -- 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 pounds_to_kilograms(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# New Conversion Functions for Temperature
def celsius_to_kelvin(c: float) -> float:
"""Convert Celsius to Kelvin."""
return c + 273.15
def kelvin_to_celsius(k: float) -> float:
"""Convert Kelvin to Celsius."""
return k - 273.15
def celsius_to_fahrenheit(c: float) -> float:
"""Convert Celsius to Fahrenheit."""
return c * 9/5 + 32
def fahrenheit_to_celsius(f: float) -> float:
"""Convert Fahrenheit to Celsius."""
return (f - 32) * 5/9
# -- Text Category --
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))
# -- Processing --
def get_safe_globals(use_degrees: bool) -> dict:
"""Return a dictionary of safe globals for expression evaluation."""
trig_funcs = {'sin', 'cos', 'tan', 'asin', 'acos', 'atan'}
safe_globals = {
"sqrt": math.sqrt,
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kilograms_to_pounds,
"kg": pounds_to_kilograms,
"C": kelvin_to_celsius,
"K": celsius_to_kelvin,
"F": celsius_to_fahrenheit,
"CF": fahrenheit_to_celsius,
"capitalize": capitalize_sentence,
"duplicates": remove_duplicates,
}
safe_globals.update({
func: (lambda f: (lambda x, f=f: convert_angle(getattr(math, f), x, use_degrees)))(func)
for func in trig_funcs.union({'asin', 'acos'})
})
return safe_globals
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)
return re.sub(r'\b(capitalize|duplicates)\(([^)]+)\)', add_quotes, expression)
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) -> Union[float, str]:
"""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
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
safe_globals = get_safe_globals(use_degrees)
expression = expression.replace("^", "**")
expression = preprocess_text_functions(expression)
error = validate_inverse_trig(expression, safe_globals)
return error or safe_evaluate(expression, safe_globals)
# -- GUI --
class CalculatorGUI(QMainWindow):
"""PySide6-based Calculator with Degrees/Radians toggle and history."""
def __init__(self):
super().__init__()
self.use_degrees = False
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')
self.entry = QLineEdit()
self.entry.setFont(font)
self.entry.returnPressed.connect(self.calculate)
self.entry.setPlaceholderText('Enter expression')
# Option 1: Enable the built-in clear button
self.entry.setClearButtonEnabled(True)
# Option 2: Add a custom clear button
# Uncomment the following block if you prefer a custom delete button
"""
import os
from PySide6.QtGui import QIcon, QAction
delete_icon_path = os.path.join(os.path.dirname(__file__), "delete_icon.png")
if os.path.exists(delete_icon_path):
clear_action = QAction(QIcon(delete_icon_path), "Clear", self)
clear_action.triggered.connect(self.entry.clear)
# Add the action to the line edit on the trailing (right) side
self.entry.addAction(clear_action, QLineEdit.ActionPosition.TrailingPosition)
else:
print("Delete icon not found. Please ensure 'delete_icon.png' is in the script directory.")
"""
self.history_text = QTextEdit()
self.history_text.setFont(font)
self.history_text.setReadOnly(True)
self.scrollbar = QScrollBar(Qt.Vertical)
self.history_text.setVerticalScrollBar(self.scrollbar)
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"]
}
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()
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, False))
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):
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 = math.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()
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 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 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}{current_text[cursor_position:]}"
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, use_degrees=self.use_degrees)
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"
self.history_text.append(f"[{mode}] {expression} = {result}")
self.history_text.verticalScrollBar().setValue(
self.history_text.verticalScrollBar().maximum()
)
def main() -> None:
"""Run the Calculator application."""
app = QApplication([])
calculator = CalculatorGUI()
calculator.show()
app.exec()
if __name__ == "__main__":
main()
Additional Customizations (Optional)
Styling the Clear Button
You can style the clear button using Qt Style Sheets to better match your application's theme. Here's an example of how to customize the appearance:
# After enabling the clear button
self.entry.setClearButtonEnabled(True)
self.entry.setStyleSheet("""
QLineEdit::clear-button {
image: url(path_to_custom_icon.png);
width: 16px;
height: 16px;
}
QLineEdit::clear-button:hover {
background-color: lightgray;
}
""")
Notes:
- Replace
path_to_custom_icon.png with the path to your custom icon.
- Adjust
width and height as needed.
- You can also add hover effects or other styles to enhance the user experience.
Handling No Text Scenario
If you want the clear button to only appear when there is text in the QLineEdit, the built-in clear button already handles this behavior. It becomes visible when the user types something and hides when the field is empty.
By following the above steps, you can seamlessly add a delete (clear) symbol to your calculator's execution field, enhancing the user experience by allowing quick clearing of input.