2012-03-08 50 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