简体   繁体   English

如何在 PyQt6 中停止(或暂停)线程?

[英]How do I stop (or pause) a thread in PyQt6?

What I am looking for is a way to stop a thread from the GUI.我正在寻找的是一种从 GUI 中停止线程的方法。 what I want to do is having a pause button, that every time it is clicked, the thread would be stopped.我想要做的是有一个暂停按钮,每次点击它时,线程都会停止。

It would look something like this (of course it is not the right syntax, is just to show an example:它看起来像这样(当然它不是正确的语法,只是为了展示一个例子:

if self.pause_button.clicked:
    #thread stops
if self.run_button.clicked:
    #thread starts again

Just to add more information, what my thread does is running a webssocket and returning the JSON value只是为了添加更多信息,我的线程所做的是运行 webssocket 并返回 JSON 值

There is no way to pause Thread.没有办法暂停线程。 However, You can imitate such a behavior by for example using Event from threading module.但是,您可以通过例如使用来自线程模块的事件来模仿这种行为。 Personally I prefer toggling instead of using two buttons.我个人更喜欢切换而不是使用两个按钮。

Here is simple code with Button implemented in PyQt6:这是在 PyQt6 中实现的带有 Button 的简单代码:

import sys
from threading import Thread, Event
from time import sleep

from PyQt6.QtWidgets import QApplication, QWidget, QPushButton


class Worker(Thread):

    def __init__(self, running_event: Event) -> None:
        self.running_event = running_event
        super().__init__()

    def run(self) -> None:
        """
        Worker is doing its job until running_event is set.
        :return: None
        """
        while self.running_event.wait():
            print("Working on something...")
            sleep(1)  # Imitate code execution


if __name__ == "__main__":
    app = QApplication(sys.argv)
    # Create and set running Event
    running_event = Event()
    running_event.set()

    widget = QWidget()
    toggle_button = QPushButton("Pause", widget)


    def toggle_running() -> None:
        """
        Toggle state of running event.
        :return: None
        """
        if running_event.is_set():
            running_event.clear()
            toggle_button.setText("Resume")
        else:
            running_event.set()
            toggle_button.setText("Pause")


    # Connect toggle_button to our toggle function
    toggle_button.clicked.connect(toggle_running)

    # Create and start worker
    worker = Worker(running_event)
    worker.setDaemon(True)
    worker.start()
    # Show widget and start application
    widget.show()
    app.exec()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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