2016-07-21 32 views
0

我想這樣做: 有一個叫'Main'的類。還有另一個類叫做'aClass'。還有一個叫做「線程」的thirth類。這是我們的線程類。 'Main'是我們的主類,我們從Main類開始我們的Thread類。 當我們的Thread類開始時,它從run()函數發出一個信號... 'Main'和'aClass'類試圖捕獲這些信號。 'Main'類能夠捕獲從Thread類發出的信號,但'aClass'無法捕獲相同的信號,因爲我沒有從'aClass'啓動QThread。我只在'aClass'中定義它。如何從QThread發出2個分類相同的信號

下面是代碼:

#!/usr/bin/env python 

from PyQt4.QtGui import * 
from PyQt4.QtCore import * 
import sys 


class Main(QMainWindow): 
    def __init__(self): 
     QMainWindow.__init__(self) 

     self.setWindowTitle("Test") 
     self.aClass = aClass() 

     self.thread = Thread() 
     self.thread.printMessage.connect(self.write) 
     self.initUI() 

    def initUI(self): 
     self.button = QPushButton("Start Process", self) 
     self.button.clicked.connect(self.startProcess) 

    def startProcess(self): 
     self.thread.start() 

    def terminateProcess(self): 
     self.thread.terminate() 

    def write(self): 
     print "Main: hello world..." 


class aClass(object): 
    def __init__(self): 
     print "aClass: I have been started..." 
     self.thread = Thread() 
     self.thread.printMessage.connect(self.write) 

    def write(self): 
     print "aClass: hello world..." 

class Thread(QThread): 
    printMessage = pyqtSignal() 

    def __init__(self): 
     QThread.__init__(self) 
     print "Thread: I have been started..." 

    def run(self): 

     self.printMessage.emit() 
     print "Thread: I emitted the message." 

if __name__ == "__main__": 
    app = QApplication(sys.argv) 
    root = Main() 
    root.show() 
    app.exec_() 

其結果是: 當程序啓動時,所述輸出爲:

aClass: I have been started... 
Thread: I have been started... 
Thread: I have been started... 

當我點擊 '啓動進程' 按鈕,則輸出爲:

Thread: I emitted the message. 
Main: hello world... 

總功率:

aClass: I have been started... 
Thread: I have been started... 
Thread: I have been started... 
Thread: I emitted the message. 
Main: hello world... 

,我想要得到的輸出,當我點擊「啓動進程」:

Thread: I emitted the message. 
Main: hello world... 
aClass: hello world... 

我想這個結果,但我並不想使用「ACLASS self.thread.start()命令「因爲我想只運行一次主題...

+0

你想從同一個線程相同的信號? –

+0

是的。我的問題解決了。 – PIC16F84A

回答

0

你在做什麼是創建在aClass對象,它是不一樣的Thread作爲Main第二Thread。您需要將Main中的self.thread的信號連接到self.aClass對象中的插槽write

你想這樣做,而不是:

class Main(QMainWindow): 
    def __init__(self): 
     QMainWindow.__init__(self) 

     self.setWindowTitle("Test") 
     self.aClass = aClass() 

     self.thread = Thread() 
     self.thread.printMessage.connect(self.write) 
     self.thread.printMessage.connect(self.aClass.write) 


... 

class aClass(object): 
    def __init__(self): 
     print "aClass: I have been started..." 
     #self.thread = Thread() #This makes a new Thread 
     #self.thread.printMessage.connect(self.write) 

    def write(self): 
     print "aClass: hello world..." 
     self.initUI() 
+1

您還可以給'self.thread'作爲'aClass .__ init__'的參數來保留當前的'connect'行。 – Frodon

+0

謝謝大家。我的問題解決了... – PIC16F84A