本文介绍了完成后将QRunnable连接到功能/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

QThread具有结束信号,当线程结束(连接到方法/函数)时,我可以执行某些操作,但是我也想使用QRunnable来执行此操作.完成后,是否可以将QRunnable线程连接到方法/函数?

QThread has a finished signal, and I am able to do something when thread is finished (connect to a method/function), however I would like to do this with QRunnable as well. Is there a way to connect the QRunnable thread to a method/function when it is done?

QThread:

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:

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的类,以便它发出信号. :

QRunnable does not have a finished signal since it is not a QObject, so a possible solution is to create another class that inherits from QObject so that it emits the signal:

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_())

这篇关于完成后将QRunnable连接到功能/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 12:09