PyQt5 Signals and Slots 'QObject has no attribute' error

ADB picture ADB · Jul 10, 2013 · Viewed 20.2k times · Source

I have been trying to find a way to update the GUI thread from a Python thread outside of main. The PyQt5 docs on sourceforge have good instructions on how to do this. But I still can't get things to work.

Is there a good way to explain the following output from an interactive session? Shouldn't there be a way to call the emit method on these objects?

>>> 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'

and

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

and

>>> 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'

Answer

zrong picture zrong · Sep 19, 2014

Following words and codes are in PyQt5 docs.

New signals should only be defined in sub-classes of QObject.They must be part of the class definition and cannot be dynamically added as class attributes after the class has been defined.

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"