1
我的程序有問題。 我想製作新的線程,並開始計算完成後,我想將setText設置爲帶有結果的標籤。 我也想要一個停止按鈕,這樣我就可以停止計算,如果他們花費太長時間。 Unfortunatley它不能正常工作,因爲在我啓動線程之後,標籤更改會立即生效,並且線程無法完成計算。 這裏是我的示例代碼:如何與PyQt5中的線程進行通信並等待結果
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_())