[英]How to quit PyQT QThread automatically when it is done?
我希望在單擊 PyQT5 中的按鈕時播放聲音。
播放聲音似乎是一個阻塞操作,因此 GUI 沒有響應。 因此,我想以非阻塞方式啟動一個新線程、播放聲音和刪除線程。
我創建了一個線程 class
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
,但這個操作似乎是阻塞的,違背了這一點。
以非阻塞方式完成后退出線程的正確方法是什么?
為什么它應該被刪除? 我沒有看到任何“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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.