完成后如何自动退出PyQT QThread?

问题描述 投票:0回答:1

我想在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,但此操作似乎被阻止,无法解决问题。

完成后以非阻塞方式退出线程的正确方法是什么?

python multithreading pyqt5 qthread
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.