pyqt4在线程中向主线程中的槽发出信号

时间:2012-03-08 08:50:38

标签: python multithreading qt signals-slots

我的主线程中有一些自定义信号,我想在其他线程中发出,但我不知道如何连接它们。有人可以发一个例子吗?

例如:

import sys, time
from PyQt4 import QtGui as qt
from PyQt4 import QtCore as qtcore

app = qt.QApplication(sys.argv)
class widget(qt.QWidget):
    signal = qtcore.pyqtSignal(str)
    def __init__(self, parent=None):
        qt.QWidget.__init__(self)
        self.signal.connect(self.testfunc)

    def appinit(self):
        thread = worker()
        thread.start()

    def testfunc(self, sigstr):
        print sigstr

class worker(qtcore.QThread):
    def __init__(self):
        qtcore.QThread.__init__(self, parent=app)

    def run(self):
        time.sleep(5)
        print "in thread"
        self.emit(qtcore.SIGNAL("signal"),"hi from thread")

def main():
    w = widget()
    w.show()
    qtcore.QTimer.singleShot(0, w.appinit)
    sys.exit(app.exec_())

main()

信号从未上升过。

1 个答案:

答案 0 :(得分:5)

您实际上是将错误的信号连接到插槽。一些修改使其按预期运行

import sys, time
from PyQt4 import QtGui as qt
from PyQt4 import QtCore as qtcore

app = qt.QApplication(sys.argv)
class widget(qt.QWidget):
    def __init__(self, parent=None):
        qt.QWidget.__init__(self)

    def appinit(self):
        thread = worker()
        self.connect(thread, thread.signal, self.testfunc)
        thread.start()

    def testfunc(self, sigstr):
        print sigstr

class worker(qtcore.QThread):
    def __init__(self):
        qtcore.QThread.__init__(self, parent=app)
        self.signal = qtcore.SIGNAL("signal")
    def run(self):
        time.sleep(5)
        print "in thread"
        self.emit(self.signal, "hi from thread")

def main():
    w = widget()
    w.show()
    qtcore.QTimer.singleShot(0, w.appinit)
    sys.exit(app.exec_())

main()
相关问题