简体   繁体   English

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

[英]pyqt4 emiting signals in threads to slots in main thread

I have some custom signals in my main thread that I would like to emit in my other threads but I'm not sure how to connect them. 我的主线程中有一些自定义信号,我想在其他线程中发出这些信号,但是我不确定如何连接它们。 Could someone post an example? 有人可以举一个例子吗?

ex: 例如:

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

signal never raised. 信号从未发出。

You actually connect the wrong signal to the slot. 您实际上将错误的信号连接到插槽。 Some modification make it run as expected 进行一些修改使其按预期运行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM