Krzysztof
Krzysztof

Reputation: 21

How to communicate with thread in PyQt5 and wait for the result

I have a problem with my program. I want to make new thread and start it, after calculations finishes I want to setText to the label with the result. I also want to have a stop button so I can stop calculations if they are taking too long. Unfortunatley it is not working right, because after I start the thread, label change is immediately and it does not work for thread to finish calculations. Here is my sample code:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys, random


class MyThread(QThread):
    def __init__(self):
        QThread.__init__(self)
        self.b=1
        self.result=0

    def run(self):
        a=0
        print(self.isRunning())
        while a<self.b and self.isRunning()==True:
            a+=1
        self.result=random.random()

class window(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setObjectName("Dialog")
        self.resize(367, 222)
        self.label = QLabel(self)
        self.label.setText("Test")
        self.label.setGeometry(QRect(30, 20, 311, 121))
        self.pushButton = QPushButton(self)
        self.pushButton2 = QPushButton(self)
        self.pushButton.setGeometry(QRect(150, 170, 75, 23))
        self.pushButton2.setGeometry(QRect(150, 140, 75, 23))
        self.pushButton.setText("Run")
        self.pushButton2.setText("Stop")
        self.pushButton.clicked.connect(self.runner)
        self.pushButton2.clicked.connect(self.stopper)
        self.mythread=MyThread()


    def runner(self):
        self.mythread.b=3000000
        self.mythread.start()
        self.label.setText(str(self.mythread.result))


    def stopper(self):
        self.mythread.terminate()


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    widget = window()
    widget.show()
    sys.exit(app.exec_())

Upvotes: 1

Views: 933

Answers (1)

Krzysztof
Krzysztof

Reputation: 21

OK, I solved my problem. since self.label.setText(str(self.mythread.result)) does not update the result, as the thread has not finished, I have added one line in myThread so it looks like this now

class MyThread(QThread):
def __init__(self):
    super(MyThread, self).__init__()
    self.b=1
    self.result=0
    self.w=window

def run(self):
    a=0
    while a<self.b and self.isRunning()==True:
        a+=1
    self.result=random.random()
    widget.label.setText(str(self.result))

while we can still stop the thread with stop button, the result will be set as text to label after calculations are finished.

Upvotes: 1

Related Questions