简体   繁体   English

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

[英]How to quit PyQT QThread automatically when it is done?

I want a sound to play when I click a button in PyQT5.我希望在单击 PyQT5 中的按钮时播放声音。

Playing a sound appears to be a blocking operation, so GUI is unresponsive.播放声音似乎是一个阻塞操作,因此 GUI 没有响应。 Thus I want to start a new thread, play sound, and delete the thread, all in a non-blocking manner.因此,我想以非阻塞方式启动一个新线程、播放声音和删除线程。

I create a thread class我创建了一个线程 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)

And run it as follows并按如下方式运行

class MainClass(...):
    ...

    def playsound(self, soundKey):
        self.thisSoundThread = playSoundThread(self.sounds[soundKey])
        self.thisSoundThread.start()

Everything works fine and is non-blocking.一切正常且无阻塞。 The only problem is that the thread does not get deleted when the sound stops playing.唯一的问题是当声音停止播放时线程不会被删除。 I have tried calling del self.thisSoundThread , but this operation seems to be blocking, defeating the point.我试过调用del self.thisSoundThread ,但这个操作似乎是阻塞的,违背了这一点。

What is the correct way to exit a thread after completion in a non-blocking way?以非阻塞方式完成后退出线程的正确方法是什么?

Why it should get deleted?为什么它应该被删除? I do not see any call of "del" and you assign it into instance so GC also doesnt because there is still existing reference.我没有看到任何“del”调用,并且您将其分配到实例中,因此 GC 也没有,因为仍然存在引用。

If you want to delete it you have to do something like this:如果要删除它,则必须执行以下操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM