Подключите QRunnable к функции / методу, когда закончите - PullRequest
1 голос
/ 28 июня 2019

QThread имеет готовый сигнал, и я могу что-то сделать, когда поток завершится (подключиться к методу / функции), однако я бы хотел сделать это и с QRunnable. Есть ли способ подключить поток QRunnable к методу / функции, когда это будет сделано?

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')

выход:

Ходовая нить

1010 * закончил *

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')

желаемый вывод:

Ходовая нить

Тема выполнена

1 Ответ

2 голосов
/ 29 июня 2019

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