43 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Python
		
	
	
	
			
		
		
	
	
			43 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Python
		
	
	
	
from PyQt6.QtWidgets import QProgressDialog
 | 
						|
from PyQt6.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.WindowModality.WindowModal)  # PyQt6: enum thay đổi
 | 
						|
    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()  # Giữ UI không bị treo
 | 
						|
 | 
						|
    progress.close()
 | 
						|
    return success_count, fail_count
 |