gpt4 book ai didi

python - 完成后将 QRunnable 连接到函数/方法

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:03 26 4
gpt4 key购买 nike

QThread 有一个完成信号,我可以在线程完成时做一些事情(连接到一个方法/函数),但是我也想用 QRunnable 做这件事。有没有办法在完成后将 QRunnable 线程连接到方法/函数?

Q线程:

class HelloWorldTask(QThread):
def __init__(self):
QThread.__init__(self)
def run(self):
import time
time.sleep(3)
print ("Running thread \n")
time.sleep(3)

hello.finished.connect(check)

def check():
print('Thread Done')

输出:

运行线程

完成

QRunnable:

instance = QThreadPool.globalInstance()


class HelloWorldTask(QRunnable):
def __init__(self):
super().__init__(self)
def run(self):
import time
time.sleep(3)
print ("Running thread \n")
time.sleep(3)

hello = HelloWorldTask()
#hello.finished.connect(check) <-- how to connect to a method/function when finished.
instance.start(hello)
print(instance.waitForDone())

def check():
print('Thread Done')

期望的输出:

运行线程

线程完成

最佳答案

QRunnable 没有完成信号,因为它不是 QObject,因此一个可能的解决方案是创建另一个继承自 QObject 的类,以便它发出信号:

from PyQt5 import QtCore


class Signals(QtCore.QObject):
finished = QtCore.pyqtSignal()


class HelloWorldTask(QtCore.QRunnable):
def __init__(self):
super().__init__()
self.signal = Signals()

def run(self):
import time

time.sleep(3)
print("Running thread \n")
time.sleep(3)
self.signal.finished.emit()


def check():
print("Thread Done")
QtCore.QCoreApplication.quit()


if __name__ == "__main__":
import sys

app = QtCore.QCoreApplication(sys.argv)
hello = HelloWorldTask()
hello.signal.finished.connect(check)
QtCore.QThreadPool.globalInstance().start(hello)
sys.exit(app.exec_())

关于python - 完成后将 QRunnable 连接到函数/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com