2012-03-12 88 views
2

我有我的問題的以下一段代碼示例。運行這個,我期望(如果你在lineedit中輸入的東西)A.updateValue插槽將被調用兩次,從而顯示'a.updatevalue called'和'a2.updatevalue called'
但是,它只被調用一次,即self.a2對象,而不是self.a對象,後者從工作線程發送到GUI線程。我該如何解決這個問題,以便這段代碼也觸發self.a對象的插槽?如何調試pyqt信號/插槽連接,可能是線程問題

謝謝 大衛

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

class A(QObject): 
    def __init__(self, name): 
     QObject.__init__(self) 
     self.name = name 
    def updateValue(self, value): 
     print(self.name + ".updatevalue called") 

class workerthread(QThread): 
    def __init__(self, parent=None): 
     QThread.__init__(self, parent) 
    def run(self): 
     a = A('a') 
     QObject.emit(self, SIGNAL("mySignal"), a) 

class Main(QMainWindow): 
    def __init__(self): 
     QMainWindow.__init__(self) 
     self.centralwidget = QWidget(self) 
     self.hbox = QHBoxLayout() 
     self.centralwidget.setLayout(self.hbox) 

    def update(self, a): 
     self.a = a 
     edit = QLineEdit("", self) 
     self.hbox.addWidget(edit) 
     edit.textChanged.connect(self.a.updateValue) 
     self.a2 = A('a2') 
     edit.textChanged.connect(self.a2.updateValue) 

if __name__ == "__main__": 
    app = QApplication(sys.argv) 
    gui = Main() 
    worker = workerthread() 
    worker.connect(worker, SIGNAL('mySignal'), gui.update) 
    worker.start() 
    gui.show() 
    sys.exit(app.exec_()) 

回答

0

定義a在初始化workerThread

class workerthread(QThread): 
    def __init__(self, parent=None): 
     QThread.__init__(self, parent) 
     self.a = A('a') 
    def run(self): 
     QObject.emit(self, SIGNAL("mySignal"), self.a) 
+0

你好,謝謝你的反應。但是,在我的生產代碼中,有多個A對象,並且我只在運行時知道將創建多少個A,因此在創建workerThread時定義所有A不是一種選擇。任何想法如何解決這個問題? – 2012-03-12 11:29:27

+0

我認爲問題在於'self.a.updateValue'SLOT與'textChanged'SIGNAL不在同一個線程中。嘗試在發出'mySignal'之前添加它:'a.moveToThread(QApplication.instance()。thread())' – 2012-03-12 18:11:23