pyqt4在线程中向主线程的插槽中发射信号 [英] pyqt4 emiting signals in threads to slots in main thread

查看:109
本文介绍了pyqt4在线程中向主线程的插槽中发射信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

例如:

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

信号从未发出.

推荐答案

您实际上将错误的信号连接到插槽.经过一些修改,使其可以按预期运行

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

这篇关于pyqt4在线程中向主线程的插槽中发射信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆