8

我一直在尝试找到一种方法来从 main 之外的 Python 线程更新 GUI 线程。sourceforge 上的PyQt5 文档对如何执行此操作有很好的说明。但我仍然无法让事情正常进行。

有没有一种很好的方法来解释交互式会话的以下输出?不应该有一种方法可以在这些对象上调用 emit 方法吗?

>>> from PyQt5.QtCore import QObject, pyqtSignal
>>> obj = QObject()
>>> sig = pyqtSignal()
>>> obj.emit(sig)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'QObject' object has no attribute 'emit'

>>> obj.sig.emit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'QObject' object has no attribute 'sig'

>>> obj.sig = pyqtSignal()
>>> obj.sig.emit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'PyQt5.QtCore.pyqtSignal' object has no attribute 'emit'
4

1 回答 1

27

以下文字和代码在PyQt5 文档中。

新信号只能在QObject 的子类中定义。它们必须是类定义的一部分,并且不能在类定义后作为类属性动态添加。

from PyQt5.QtCore import QObject, pyqtSignal

class Foo(QObject):

    # Define a new signal called 'trigger' that has no arguments.
    trigger = pyqtSignal()

    def connect_and_emit_trigger(self):
        # Connect the trigger signal to a slot.
        self.trigger.connect(self.handle_trigger)

        # Emit the signal.
        self.trigger.emit()

    def handle_trigger(self):
        # Show that the slot has been called.

        print "trigger signal received"
于 2014-09-19T09:43:33.233 回答