-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidget_utilities_DevNB.py
More file actions
803 lines (644 loc) · 29.4 KB
/
Copy pathwidget_utilities_DevNB.py
File metadata and controls
803 lines (644 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.17.3
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# %% [markdown]
# # Widget Utilities Base Class Demo
#
# This notebook demonstrates the `WidgetUtilities` base class, which provides a standard
# pattern for initializing PySide6 widgets with consistent structure and debug capabilities.
# %% [markdown]
# # Initial author GProtoZeroW Sept 2025
#
# # Acknowledgments
#
# This project's documentation and code comments were refined with the assistance of Claude Opus 4 (Anthropic) for proofreading, spelling corrections, and clarity improvements. The AI assistant helped ensure consistent code, code formatting, proper grammar, and clear technical writing throughout the codebase.
# %% [markdown]
# # Qt Event Loop Integration
# %%
# %gui qt
# %% [markdown]
# # Logging (loguru) Setup
# %%
import sys
from pathlib import Path
from datetime import datetime
from loguru import logger
# Configure logging
CONSOLE_LOG_LEVEL = "DEBUG"
FILE_LOG_LEVEL = "DEBUG"
# Remove default handler
logger.remove()
# Setup log file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
LOG_FILE = Path.cwd() / "logs" / f"widget_utilities_demo_{timestamp}.log"
LOG_FILE.parent.mkdir(exist_ok=True)
# Add handlers
console_handler_id = logger.add(
sys.stdout,
format="<level>{level: <8}</level> | <level>{message}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>",
level=CONSOLE_LOG_LEVEL,
colorize=True,
enqueue=False
)
file_handler_id = logger.add(
LOG_FILE,
format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} | {message}",
level=FILE_LOG_LEVEL,
rotation="100 MB",
retention=5 # Just the number, not "5 files"
)
logger.success("Logging configured")
# %% [markdown]
# # Imports
# %% [markdown]
# ## External
# %%
from PySide6 import QtWidgets, QtCore, QtGui
import sys
from contextlib import contextmanager
import base64
from io import BytesIO
from PIL import Image
import matplotlib.pyplot as plt
logger.success("All need modules imported")
# %% [markdown]
# # WidgetUtilities Base Class
# %% [markdown]
# ## Documentation
#
# This class serves three purposes:
#
# ### Part 1: Enforcing Widget Development Standards
#
# This class enforces a standard set of methods to override when creating new widget classes, and provides an auto-initialization sequence runner for child classes.
#
# **Methods to Override:**
#
# - **`gui_layout_init`**: Instantiate child widgets and set up layouts for the widget under development
# - **`gui_sizing_init`**: Set sizing constraints (min/max sizes, etc.) for the widget under development
# - **`gui_styling_init`**: Apply custom styling that differs from the parent/global styles
# - **`gui_wiring_init`**: Connect signals from widgets instantiated in `gui_layout_init` to slot methods
#
# **Initialization Sequence:**
#
# The `_widget_startup_init_calls()` method should be called in the child class's `__init__` method. It executes methods in this order:
#
# 1. Layout
# 2. Sizing
# 3. Styling
# 4. Wiring
#
# This sequence is the most common (though not absolute) Qt widget setup pattern. By setting up wiring last, we minimize unintended signal firing during the setup process (e.g., resize events triggering before styling is complete).
#
# ### Part 2: Development Utilities
#
# - **`temp_block_widgets_signals()`**: Context manager that temporarily blocks signals from multiple widgets. Essential for updating multiple interconnected widgets without triggering cascading signals. Automatically restores previous signal states on exit.
#
# ### Part 3: Debug and Automation Utilities
#
# Three methods aid in debugging and automated testing of PySide widgets:
#
# - **`set_debug_tooltips()`**: Adds (or appends to existing tooltips) the widget's attribute name and type when hovering. Invaluable for identifying widgets in the rendered UI.
#
# - **`capture_widget_info()`**: Captures information for all child widgets, returning a dictionary keyed by widget attribute name containing:
# - `location`: (x, y) screen coordinates of the widget's top-left corner in pixels
# - `size`: (width, height) of the widget in pixels
# - `image_base64`: Base64 encoded PNG image string (for image recognition with tools like PyAutoGUI's `locateOnScreen()`)
# - `type`: Widget class name
#
# - **`show_widget_image()`**: Static method to display the base64 encoded widget images from `capture_widget_info()` using matplotlib
#
# ### Note on ABC Implementation
#
# While referred to as an "Abstract Base Class" (ABC), this doesn't use Python's built-in `abc` module due to metaclass conflicts with Qt. Instead, it uses `raise NotImplementedError` - simpler and equally effective for methods that will always be called during runtime.
# %% [markdown]
# ## Code
# %%
# For demo purposes, we'll redefine the class here in this notebook. In practical usage, you'd import:
# from pyside_refrances.widget_utilities import WidgetUtilities
class WidgetUtilities:
"""
Abstract base class providing common widget utilities and initialization structure.
Provides debug tools for widget inspection and a standard initialization sequence
for GUI widgets. Subclasses must implement the abstract initialization methods.
"""
# ==================================
# === GUI Setup Abstract Methods ===
# ==================================
def _widget_startup_init_calls(self):
"""Call all GUI initialization methods in the proper sequence."""
self.gui_layout_init()
self.gui_sizing_init()
self.gui_styling_init()
self.gui_wiring_init()
def gui_layout_init(self):
"""Initialize and arrange all GUI elements."""
raise NotImplementedError("Subclass must implement gui_layout_init")
def gui_sizing_init(self):
"""Set widget size constraints and properties."""
raise NotImplementedError("Subclass must implement gui_sizing_init")
def gui_styling_init(self):
"""Apply widget styling and appearance settings."""
raise NotImplementedError("Subclass must implement gui_styling_init")
def gui_wiring_init(self):
"""Connect widget signals to their slots."""
raise NotImplementedError("Subclass must implement gui_wiring_init")
# ========================
# === Usage Utilities ===
# ========================
@contextmanager
def temp_block_widgets_signals(self, *widgets):
"""
Context manager to temporarily block signals for multiple widgets.
Blocks all signals from the specified widgets for the duration of the
context, then restores their previous signal state. Useful for preventing
circular signal emission when programmatically updating widget values.
Args:
*widgets: Variable number of QWidget instances to block
Example:
with self.temp_block_widgets_signals(self.lineEdit, self.comboBox):
self.lineEdit.setText("new value")
self.comboBox.setCurrentIndex(2)
# No signals emitted from these widgets during this block
Note:
If a widget was already blocking signals before entering the context,
it will remain blocked after exiting.
"""
# Store original signal blocking states
original_states = []
for widget in widgets:
if isinstance(widget, QtCore.QObject): # Check it's a Qt object
original_states.append((widget, widget.blockSignals(True)))
else:
logger.warning(f"Skipping non-QObject: {widget}")
original_states.append((widget, None))
try:
yield
finally:
# Restore original signal blocking states
for widget, original_state in original_states:
if original_state is not None: # Was a valid QObject
widget.blockSignals(original_state)
# ===================
# === Debug Tools ===
# ===================
def set_debug_tooltips(self):
"""
Set debug tooltips on all widgets showing their variable names.
If a widget already has a tooltip, appends debug info to it.
Otherwise, sets the debug tooltip directly.
"""
for attr_name in dir(self):
attr = getattr(self, attr_name, None)
if isinstance(attr, QtWidgets.QWidget):
debug_info = f"Widget: {attr_name}\nType: {type(attr).__name__}"
existing_tooltip = attr.toolTip()
if existing_tooltip:
# Append debug info to existing tooltip
attr.setToolTip(f"{existing_tooltip}\n\n--- Debug Info ---\n{debug_info}")
else:
# No existing tooltip, just set debug info
attr.setToolTip(debug_info)
if isinstance(self, QtWidgets.QWidget):
debug_info = f"Widget: {self.__class__.__name__}"
existing_tooltip = self.toolTip()
if existing_tooltip:
self.setToolTip(f"{existing_tooltip}\n\n--- Debug Info ---\n{debug_info}")
else:
self.setToolTip(debug_info)
def capture_widget_info(self):
"""
Capture widget images and locations for automation.
Iterates through all visible QWidget attributes and captures their
screen position, size, and appearance. Intended for future use with
pyautogui or similar automation tools.
Returns:
dict: Widget information indexed by attribute name. Each entry contains:
{
'location': tuple[int, int], # (x, y) global screen coordinates of the top-left corner
'size': tuple[int, int], # (width, height) in pixels
'image_base64': str, # Base64 encoded PNG image
'type': str # Widget class name (e.g., 'QPushButton')
}
Example:
>>> info = widget.capture_widget_info()
>>> info['self']['type'] # The parent widget itself
'FileFolderSelectorQWidget'
>>> info['submit_QPushButton']['location']
(100, 200)
"""
widget_info = {}
# First, capture the parent widget itself if it's a QWidget
if isinstance(self, QtWidgets.QWidget) and self.isVisible():
# Get screen position of widget's top-left corner
global_pos = self.mapToGlobal(QtCore.QPoint(0, 0))
location = (global_pos.x(), global_pos.y())
size = (self.width(), self.height())
# Create a pixmap (off-screen image) of the widget's size
pixmap = QtGui.QPixmap(self.size())
# Render the widget's visual appearance into the pixmap
self.render(pixmap)
# Convert pixmap to base64 string for storage/transmission
byte_array = QtCore.QByteArray()
buffer = QtCore.QBuffer(byte_array)
buffer.open(QtCore.QIODevice.WriteOnly)
pixmap.save(buffer, "PNG") # Save pixmap as PNG into buffer
base64_str = base64.b64encode(byte_array.data()).decode()
widget_info['self'] = {
'location': location,
'size': size,
'image_base64': base64_str,
'type': type(self).__name__
}
# Then capture all child widgets
for attr_name in dir(self):
attr = getattr(self, attr_name, None)
if isinstance(attr, QtWidgets.QWidget) and attr.isVisible():
# Get widget's position in global screen coordinates
global_pos = attr.mapToGlobal(QtCore.QPoint(0, 0))
location = (global_pos.x(), global_pos.y())
size = (attr.width(), attr.height())
# Create pixmap and render widget appearance
pixmap = QtGui.QPixmap(attr.size())
attr.render(pixmap)
# Convert to base64 for easy storage/transmission
byte_array = QtCore.QByteArray()
buffer = QtCore.QBuffer(byte_array)
buffer.open(QtCore.QIODevice.WriteOnly)
pixmap.save(buffer, "PNG")
base64_str = base64.b64encode(byte_array.data()).decode()
widget_info[attr_name] = {
'location': location,
'size': size,
'image_base64': base64_str,
'type': type(attr).__name__
}
return widget_info
@staticmethod
def show_widget_image(widget_info, widget_name):
"""
Display captured widget image with formatted metadata.
Args:
widget_info: Dictionary from capture_widget_info()
widget_name: Name of widget to display
"""
img_data = base64.b64decode(widget_info[widget_name]['image_base64'])
img = Image.open(BytesIO(img_data))
# Create figure with better spacing
fig, ax = plt.subplots(figsize=(8, 5))
# Display image
ax.imshow(img)
ax.axis('off')
# Add border around image
ax.add_patch(plt.Rectangle((0, 0), img.width-1, img.height-1,
fill=False, edgecolor='gray', linewidth=2))
# Format widget info
info = widget_info[widget_name]
# Main title - widget name and type
ax.set_title(f"{widget_name} ({info['type']})",
fontsize=14, fontweight='bold', pad=10)
# Subtitle with location and size info
location_text = f"Widget Top-Left corner location in screen space: {info['location']} • Size: {info['size'][0]}×{info['size'][1]}px"
fig.text(0.5, 0.92, location_text,
ha='center', fontsize=10, color='gray')
# Tighten layout
plt.tight_layout()
plt.subplots_adjust(top=0.85)
plt.show()
logger.success("WidgetUtilities class defined")
# %% [markdown]
# # Helper Functions
# %% [markdown]
# ## close_qt_windows
# Utility function for closing any lingering Qt windows before creating new widgets.
# Useful during development to avoid window clutter.
# %%
def close_qt_windows():
"""
Close all visible top-level Qt windows.
Iterates through all top-level widgets in the application and closes
any that are currently visible. Useful for cleaning up during
interactive development in notebooks.
Returns:
int: Number of windows closed
"""
closed_count = 0
for widget in QtWidgets.QApplication.topLevelWidgets():
if widget.isVisible():
logger.debug(f"Closing widget: {widget.objectName() or widget.__class__.__name__}")
widget.close()
closed_count += 1
if closed_count:
logger.info(f"Closed {closed_count} Qt window(s)")
else:
logger.debug("No visible Qt windows to close")
return closed_count
# %% [markdown]
# # Connect to Qt QApplication for in Notebook Demonstration
# %%
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
logger.debug("Created new QApplication")
else:
logger.debug("Connected to existing QApplication")
# %% [markdown]
# # Example Implementation: SimpleCalculatorWidget
#
# This demonstrates how to use `WidgetUtilities` to create a simple calculator widget with consistent initialization patterns, followed by a demonstration of the debug tools in `WidgetUtilities` using Qt's Jupyter Notebook integration.
#
# In defining the `SimpleCalculatorWidget` below we will show:
# 1. How to properly override all required methods from `WidgetUtilities`
# 2. The initialization flow in action
# %% [markdown]
# ## Code
# %%
class SimpleCalculatorWidget(QtWidgets.QWidget, WidgetUtilities):
"""A minimal calculator demonstrating WidgetUtilities usage."""
result_changed = QtCore.Signal(float)
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("SimpleCalculator")
# Initialize calculation counter
self._calc_count = 0
# Initialize using the standard pattern
self._widget_startup_init_calls()
logger.info("SimpleCalculatorWidget initialized")
# =================
# === GUI Setup ===
# =================
def gui_layout_init(self):
"""Initialize and arrange all GUI elements."""
logger.debug("Setting up calculator layout")
# Main layout
self.main_layout = QtWidgets.QVBoxLayout(self)
# Display
self.display_QLineEdit = QtWidgets.QLineEdit("0")
self.display_QLineEdit.setReadOnly(True)
self.display_QLineEdit.setAlignment(QtCore.Qt.AlignRight)
self.main_layout.addWidget(self.display_QLineEdit)
# Number input row
input_layout = QtWidgets.QHBoxLayout()
self.number1_QSpinBox = QtWidgets.QSpinBox()
self.number1_QSpinBox.setRange(-1000, 1000)
self.number1_QSpinBox.setValue(10)
self.operation_QComboBox = QtWidgets.QComboBox()
self.operation_QComboBox.addItems(["+", "-", "*", "/"])
self.number2_QSpinBox = QtWidgets.QSpinBox()
self.number2_QSpinBox.setRange(-1000, 1000)
self.number2_QSpinBox.setValue(5)
self.calculate_QPushButton = QtWidgets.QPushButton("Calculate")
input_layout.addWidget(self.number1_QSpinBox)
input_layout.addWidget(self.operation_QComboBox)
input_layout.addWidget(self.number2_QSpinBox)
input_layout.addWidget(self.calculate_QPushButton)
self.main_layout.addLayout(input_layout)
# Add preset buttons row
preset_layout = QtWidgets.QHBoxLayout()
self.reset_QPushButton = QtWidgets.QPushButton("Reset to Defaults")
self.preset1_QPushButton = QtWidgets.QPushButton("Preset: 100 * 2")
self.preset2_QPushButton = QtWidgets.QPushButton("Preset: 50 / 10")
preset_layout.addWidget(self.reset_QPushButton)
preset_layout.addWidget(self.preset1_QPushButton)
preset_layout.addWidget(self.preset2_QPushButton)
self.main_layout.addLayout(preset_layout)
def gui_wiring_init(self):
"""Connect widget signals to their slots."""
logger.debug("Connecting signals and slots")
self.calculate_QPushButton.clicked.connect(self.calculate_QPushButton_clicked_action)
self.number1_QSpinBox.valueChanged.connect(self.calculate_QPushButton_clicked_action)
self.number2_QSpinBox.valueChanged.connect(self.calculate_QPushButton_clicked_action)
self.operation_QComboBox.currentTextChanged.connect(self.calculate_QPushButton_clicked_action)
# Connect preset buttons
self.reset_QPushButton.clicked.connect(self.reset_to_defaults)
self.preset1_QPushButton.clicked.connect(self.load_preset_multiply)
self.preset2_QPushButton.clicked.connect(self.load_preset_divide)
def gui_sizing_init(self):
"""Set widget size constraints and properties."""
logger.debug("Setting size constraints")
self.setMinimumSize(300, 150)
if not self.parent():
self.resize(400, 180)
self.setWindowTitle(self.objectName())
def gui_styling_init(self):
"""Apply widget styling and appearance settings."""
logger.debug("Applying styles")
# Example of minimal styling that works with any theme
style = """
QLineEdit#display_QLineEdit {
font-size: 18px;
font-weight: bold;
padding: 5px;
}
"""
self.display_QLineEdit.setObjectName("display_QLineEdit")
self.setStyleSheet(style)
# ===================
# === GUI Backend ===
# ===================
@QtCore.Slot()
def calculate_QPushButton_clicked_action(self):
"""Handle calculation when button clicked or values changed."""
self._calc_count += 1
num1 = self.number1_QSpinBox.value()
num2 = self.number2_QSpinBox.value()
operation = self.operation_QComboBox.currentText()
logger.debug(f"Performing calculation #{self._calc_count}: {num1} {operation} {num2}")
try:
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/" and num2 != 0:
result = num1 / num2
else:
result = "Error"
self.display_QLineEdit.setText(str(result))
if isinstance(result, (int, float)):
self.result_changed.emit(result)
except Exception as e:
logger.error(f"Calculation error: {e}")
self.display_QLineEdit.setText("Error")
@QtCore.Slot()
def reset_to_defaults(self):
"""Reset all inputs to default values without triggering multiple calculations."""
logger.info("Resetting to defaults WITH signal blocking")
# Without blocking, this would trigger 3 calculations!
with self.temp_block_widgets_signals(
self.number1_QSpinBox,
self.number2_QSpinBox,
self.operation_QComboBox
):
self.number1_QSpinBox.setValue(10)
self.number2_QSpinBox.setValue(5)
self.operation_QComboBox.setCurrentText("+")
# Now trigger one calculation after all values are set
self.calculate_QPushButton_clicked_action()
logger.info("Reset complete - only one calculation performed")
@QtCore.Slot()
def load_preset_multiply(self):
"""Load a multiplication preset without intermediate calculations."""
logger.info("Loading multiplication preset WITH signal blocking")
with self.temp_block_widgets_signals(
self.number1_QSpinBox,
self.number2_QSpinBox,
self.operation_QComboBox
):
self.number1_QSpinBox.setValue(100)
self.operation_QComboBox.setCurrentText("*")
self.number2_QSpinBox.setValue(2)
# Single calculation after all values set
self.calculate_QPushButton_clicked_action()
@QtCore.Slot()
def load_preset_divide(self):
"""Load a division preset - demonstrates preventing intermediate error."""
logger.info("Loading division preset WITH signal blocking")
# This is especially useful here - without blocking, changing to division
# might temporarily create a divide-by-zero if number2 is currently 0!
with self.temp_block_widgets_signals(
self.number1_QSpinBox,
self.number2_QSpinBox,
self.operation_QComboBox
):
self.operation_QComboBox.setCurrentText("/")
self.number2_QSpinBox.setValue(10) # Set divisor first to avoid /0
self.number1_QSpinBox.setValue(50)
self.calculate_QPushButton_clicked_action()
# %% [markdown]
# ## Widget Demonstration
# The demonstration will show:
# 1. Using `set_debug_tooltips()` to inspect the widget hierarchy
# 2. Using `capture_widget_info()` to gather automation data
# %%
#use helper function to close any exsiting qt windows before showing the window to used here
close_qt_windows()
# Create and show the calculator
calculator = SimpleCalculatorWidget()
calculator.result_changed.connect(lambda r: logger.info(f"Result: {r}"))
calculator.show()
logger.success("Calculator widget displayed")
# %% [markdown]
# **Do not close the `SimpleCalculatorWidget` instance window yet.**
#
# It needs to remain open to demonstrate the debug tools in the following cells.
# %% [markdown]
# ### `temp_block_widgets_signals` Demonstration
# This is difficult to demonstrate, but here goes. Without temp_block_widgets_signals, any change in value causes the full calculation to proceed immediately, as shown in the following cells:
# %%
calculator.number1_QSpinBox.setValue(100) # Triggers calculation
logger.warning("Calculation triggered as soon as number1_QSpinBox value change!")
# %%
calculator.operation_QComboBox.setCurrentText("*") # Triggers calculation
logger.warning("Calculation triggered as soon as operation_QComboBox value change!")
# %%
calculator.number2_QSpinBox.setValue(2) # Triggers calculation
logger.warning("Calculation triggered as soon as number2_QSpinBox value change!")
# %% [markdown]
# The issue is we often want to momentarily restrict signal emission when changing widget values/states without triggering signals, either to control behavior more granularly or to prevent near-infinite loop behavior in the GUI.
# For example, in calculator.reset_to_defaults, the temp_block_widgets_signals context manager blocks output signals from the three widgets while setting their values without triggering calculations. Upon exiting the context scope, signals are automatically re-enabled to return to normal operation:
#
#
# ``` python
# class SimpleCalculatorWidget(QtWidgets.QWidget, WidgetUtilities):
#
# ...
#
# def reset_to_defaults(self):
# """Reset all inputs to default values without triggering multiple calculations."""
# logger.info("Resetting to defaults WITH signal blocking")
#
# # Without blocking, this would trigger 3 calculations!
# with self.temp_block_widgets_signals(
# self.number1_QSpinBox,
# self.number2_QSpinBox,
# self.operation_QComboBox
# ):
# self.number1_QSpinBox.setValue(10)
# self.number2_QSpinBox.setValue(5)
# self.operation_QComboBox.setCurrentText("+")
#
# # Now trigger one calculation after all values are set
# self.calculate_QPushButton_clicked_action()
# logger.info("Reset complete - only one calculation performed")
#
# ...
# ```
#
# Thus when we call calculator.reset_to_defaults(), only one calculation occurs when we want it to (at the end of the method), not one for each value change:
# %%
calculator.reset_to_defaults()
# %% [markdown]
# ### `set_debug_tooltips` Demonstration
#
# After running the following cell, `set_debug_tooltips` will add debug tooltips to all widgets in the `SimpleCalculatorWidget` instance. To view them, simply hover your cursor over any widget and the tooltip should appear.
#
# Due to how widget bounding boxes work, you may need to reposition your cursor slightly to trigger the tooltip for the specific widget you want to inspect.
# %%
# Enable debug tooltips to see widget names on hover
calculator.set_debug_tooltips()
logger.info("Debug tooltips enabled - hover over widgets to see their names")
# %% [markdown]
# ### `capture_widget_info` Demonstration
# Makes python dict of all widget including the parent widget with each widget name being the key and the values being a further sub dict of:
# - `location`: Tuple of (x, y) global screen coordinates of the widget's top-left corner
# - `size`: Tuple of (width, height) dimensions of the widget in pixels
# - `image_base64`: Base64-encoded PNG screenshot of the widget
# - `type`: String name of the widget's class (e.g., 'QLabel', 'QPushButton', 'QLineEdit')
# %%
# Capture widget information (for future automation with pyautogui)
widget_info = calculator.capture_widget_info()
logger.info(f"Captured info for {len(widget_info)} widgets")
for widget_name, info in widget_info.items():
logger.debug(f"{widget_name}: Location={info['location']}, Size={info['size']}, Widget_Class=`{info['type']}` ")
# %% [markdown]
# ### `show_widget_image` Demonstration
#
# Displays captured images of the source widget and all child widgets.
# %%
for widget_name in widget_info.keys():
WidgetUtilities.show_widget_image(widget_info, widget_name)
# %%
# %% [markdown]
# ## Cleanup
# %%
#Close qt windows
close_qt_windows()
# Force close Qt Application (warning: can not use perfor any subsequent Qt usage in Jupyter)
app = QtWidgets.QApplication.instance()
if app:
app.quit()
logger.info("Qt Application forcefully closed")
# %% [markdown]
# ## Key Takeaways
#
# 1. **Consistent Structure**: The `WidgetUtilities` base class enforces a consistent
# initialization pattern across all widgets.
#
# 2. **Clear Separation**: Layout, wiring, sizing, and styling are separated into
# distinct methods for clarity.
#
# 3. **Debug Support**: Built-in debug tooltips and widget capture make development
# and testing easier.
#
# 4. **Signal/Slot Naming**: The `[widget]_[signal]_action` pattern makes it clear
# what each slot handles.
#
# 5. **Future Automation**: The `capture_widget_info()` method prepares widgets for
# automated testing with tools like pyautogui.
#
# This pattern scales well from simple widgets like this calculator to complex
# interfaces with matplotlib integration, pandas data handling, and more.
# %%