40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
from PyQt5.QtWidgets import QProgressDialog
|
|
from PyQt5.QtCore import Qt, QCoreApplication
|
|
|
|
def run_with_progress(items, handler, message="Loading...", cancel_text="Cancel", parent=None):
|
|
"""
|
|
Run the handler for each item in `items` and display a loading progress bar.
|
|
- items: iterable (list, tuple, ...)
|
|
- handler: function to process each item (may raise errors, won't crash the app)
|
|
- message: message displayed on the dialog
|
|
- cancel_text: cancel button text
|
|
- parent: optional parent QWidget
|
|
"""
|
|
total = len(items)
|
|
if total == 0:
|
|
return 0, 0
|
|
|
|
progress = QProgressDialog(message, cancel_text, 0, total, parent)
|
|
progress.setWindowModality(Qt.WindowModal)
|
|
progress.setMinimumDuration(0)
|
|
progress.setValue(0)
|
|
|
|
success_count = 0
|
|
fail_count = 0
|
|
|
|
for i, item in enumerate(items):
|
|
if progress.wasCanceled():
|
|
break
|
|
try:
|
|
handler(item)
|
|
success_count += 1
|
|
except Exception as e:
|
|
print(f"Error processing item {i}: {e}")
|
|
fail_count += 1
|
|
|
|
progress.setValue(i + 1)
|
|
QCoreApplication.processEvents() # Prevent UI freezing
|
|
|
|
progress.close()
|
|
return success_count, fail_count
|