2012-03-08 34 views
2

在冒落线程信号插槽我在主线程一些自定义的信号,我想在我的其他线程发出,但我不知道如何将它们连接起来。有人可以发表一个例子吗?PyQt4的主线程

例如:

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

信号从未提出。

+0

我忘了提及它们是新风格的信号 – user393899 2012-03-08 09:01:05

+0

您是否使用QThread或python的线程? – Dikei 2012-03-08 09:28:23

+0

我使用的QThread – user393899 2012-03-08 09:41:48

回答

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() 
+0

感谢您的帮助。 – user393899 2012-03-08 13:37:17

+0

PyQt的文件说:“家长的说法,如果不是无,导致自我使用Qt,而不是PyQt的所有。” qtcore.QThread .__ init __(self,parent = app)如何在这里工作?应用参数来自哪里? – user937284 2014-01-11 14:22:11

+0

应用程序是定义线路5至于为什么'使用'qtcore.QThread .__初始化__(个体,父母= APP),我不知道。我只是从原始代码中复制它。 – Dikei 2014-01-13 03:50:03