当我单击PyQT5中的按钮时,我想播放声音。
播放声音似乎是一项阻止操作,因此GUI没有响应。因此,我想以无阻塞的方式启动一个新线程,播放声音并删除该线程。
我创建了一个线程类
class playSoundThread(QtCore.QThread):
def __init__(self, soundpath):
QtCore.QThread.__init__(self)
self.soundpath = soundpath
def __del__(self):
self.wait()
print("Thread exited")
def run(self):
playsound(self.soundpath)
并按以下方式运行
class MainClass(...):
...
def playsound(self, soundKey):
self.thisSoundThread = playSoundThread(self.sounds[soundKey])
self.thisSoundThread.start()
一切正常,并且没有阻塞。唯一的问题是声音停止播放时不会删除线程。我曾尝试调用del self.thisSoundThread
,但此操作似乎正在阻塞,使问题无法解决。
以非阻塞方式完成后退出线程的正确方法是什么?
答案 0 :(得分:1)
为什么要删除它?我看不到“ del”的任何调用,您将其分配到实例中,因此GC也没有,因为仍然存在引用。
如果要删除它,则必须执行以下操作:
class MainClass(...):
...
def playsound(self, soundKey):
self.thisSoundThread = playSoundThread(self.sounds[soundKey])
self.thisSoundThread.finished.connect(self.threadfinished)
self.thisSoundThread.start()
def threadfinished(self)
del self.thisSoundThread
# or set it to None