【问题标题】:pyqt4 emiting signals in threads to slots in main threadpyqt4在线程中向主线程中的插槽发出信号
【发布时间】:2012-03-08 08:50:38
【问题描述】:

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

例如:

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

从未发出信号。

【问题讨论】:

  • 我忘了说它们是新风格的信号
  • 你用的是QThread还是python的线程?
  • 你能不能发一个不工作的例子,因为信号和槽默认应该跨QThread工作,不需要特殊处理
  • 有点太简单了。你能修改它,这样我就可以复制并运行了:)

标签: python multithreading qt signals-slots


【解决方案1】:

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

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

【讨论】:

  • PyQT 文档说:“父参数,如果不是 None,会导致 self 归 Qt 而不是 PyQt 所有。” qtcore.QThread.__init__(self, parent=app) 在这里如何工作? app 参数从何而来?
  • app 在第 5 行定义。至于为什么使用qtcore.QThread.__init__(self, parent=app),我不知道。我只是从原始代码中复制的。
  • 我运行了该代码,但我遇到了问题。在 def testfunc 期间显示的小部件冻结。
  • 如果它被冻结,则意味着它不是在单独的线程中运行,而是在 GUI 所在的主线程中运行。
猜你喜欢
  • 1970-01-01
  • 2018-04-29
  • 2020-04-30
  • 1970-01-01
  • 2014-12-18
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 2022-08-03
相关资源
最近更新 更多