2014-11-03 16 views
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_()) 

回答

1

好的,我解決了我的問題。 因爲self.label.setText(STR(self.mythread.result))不更新結果,線程還沒有完成,我在MyThread的添加一條線,所以它看起來是現在這個樣子

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

雖然我們仍然可以通過停止按鈕停止線程,但計算結束後,結果將被設置爲文本來標記。