我有一个小 GUI,在显示的图像上显示不同的层。在某些时候,我想将带有所有可视化图层的当前图像存储到磁盘,同时继续使用 GUI。图像相当大(存储大约需要 5 秒),所以我想将保存的内容卸载到后台线程中。
我尝试了不同的方法,但都没有奏效。最小的工作示例(仍然需要 PNG 进行测试,抱歉):
import sys
import threading
from PIL import Image
from PIL.ImageQt import ImageQt
from PyQt5.QtCore import QThread, pyqtSignal, QRunnable, QThreadPool
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QSizePolicy, QAction, QToolBar
class StorageQRunnable(QRunnable):
def __init__(self,
pixmap: QPixmap,
target_path: str):
super(StorageQRunnable, self).__init__()
self.pixmap = pixmap
self.target_path = target_path
def run(self):
print("Starting to write image in QRunnable.")
self.pixmap.save(self.target_path, "PNG")
print("Done writing image in QRunnable.")
class StorageQThread(QThread):
signal = pyqtSignal("PyQt_PyObject")
def __init__(self,
pixmap: QPixmap,
target_path: str):
super(StorageQThread, self).__init__()
self.pixmap = pixmap
self.target_path = target_path
def run(self):
print("Starting to write image in QThread.")
self.pixmap.save(self.target_path, "PNG")
print("Done writing image in QThread.")
self.signal.emit(0)
class StorageThread(threading.Thread):
def __init__(self,
pixmap: QPixmap,
target_path: str):
super(StorageThread, self).__init__()
self.pixmap = pixmap
self.target_path = target_path
def run(self):
print("Starting to write image in threading.Thread.")
self.pixmap.save(self.target_path, "PNG")
print("Done writing image in threading.Thread.")
简短手册:
开始
按Ctrl+F查看来自 GUI 线程的控制台输出(一次或多次)
按Ctrl+B开始将大 PNG 存储在后台线程中
继续按Ctrl+ F,在图像被存储之前什么都没有发生,并且所有事件都只在之后处理(GUI 不可用)
Ctrl通过+退出Q
随意评论不同的方法,即 的用法threading.Thread
、用法QThread
或用法QRunnable
,所有结果都相同:将像素图存储为 PNG(实际上应该在后台线程中发生)会阻塞 GUI。
犯罪嫌疑人X
相关分类