写了一个显示Qt正在处理内容的等待动画,任务另开一个线程执行,执行完后自动关闭动画
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication, QMessageBox, QDialog, QVBoxLayout
from PyQt5.QtCore import pyqtSignal, QTimer, QThread, QObject, Qt
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QLabel
from PyQt5.QtGui import QMovie, QIconclass WorkerThread(QThread):finished = pyqtSignal(str)def __init__(self, task, *args):super().__init__()self.task = taskself.args = argsdef run(self):# 执行任务,并传递参数result = self.task(*self.args)self.finished.emit(result)class GifPlayer(QDialog):def __init__(self, parent, gif_path, task, *args):super().__init__(parent, Qt.FramelessWindowHint | Qt.Tool) # 设置窗口标志self.setAttribute(Qt.WA_TranslucentBackground) # 设置窗口背景透明# 设置样式表来确保QLabel的背景透明self.setStyleSheet("QLabel { background-color: transparent; }")self.setParent(parent)self.label = QLabel(self)layout = QVBoxLayout(self)layout.addWidget(self.label)self.movie = QMovie(gif_path)self.label.setMovie(self.movie)self.label.show()self.worker_thread = WorkerThread(task, *args)self.worker_thread.finished.connect(self.on_task_finished)def start_animation(self):self.label.show()self.movie.start()self.worker_thread.start() # 开始线程def stop_animation(self):self.movie.stop()def on_task_finished(self, result):self.movie.stop()# dosomething....self.reject()
调用演示:
gif_player = GifPlayer(self, './waiting/waiting.gif', self.ReadAndSetText, filename) # './waiting/waiting.gif'这个是gif的路径,self.ReadAndSetText这个是我要处理的任务函数
gif_player.start_animation()
gif_player.exec_()
效果展示: