如何调试pyqt信号/插槽连接,可能是线程问题

时间:2012-03-12 00:16:43

标签: multithreading connection pyqt signals-slots

我有以下问题的示例代码。运行这个,我希望(如果你在lineedit中键入内容),将会调用A.updateValue插槽两次,从而显示'a.updatevalue called'和'a2.updatevalue called' 但是,它只调用一次,即self.a2对象而不是self.a对象,后者从工作线程发送到GUI线程。我该如何解决这个问题,以便这段代码也能触发self.a对象的插槽?

谢谢你, 大卫

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

1 个答案:

答案 0 :(得分: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)