PyQt5 信号和插槽“QObject 没有属性"错误 [英] PyQt5 Signals and Slots 'QObject has no attribute' error

查看:37
本文介绍了PyQt5 信号和插槽“QObject 没有属性"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<预><代码>>>>从 PyQt5.QtCore 导入 QObject,pyqtSignal>>>obj = QObject()>>>信号 = pyqtSignal()>>>对象.emit(sig)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'QObject' 对象没有属性 'emit'

<预><代码>>>>obj.sig.emit()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'QObject' 对象没有属性 'sig'

<预><代码>>>>obj.sig = pyqtSignal()>>>obj.sig.emit()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'PyQt5.QtCore.pyqtSignal' 对象没有属性 'emit'

解决方案

以下文字和代码在 PyQt5 文档.

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

from PyQt5.QtCore import QObject, pyqtSignal类 Foo(QObject):# 定义一个没有参数的名为trigger"的新信号.触发器 = pyqtSignal()def connect_and_emit_trigger(self):# 将触发信号连接到插槽.self.trigger.connect(self.handle_trigger)# 发出信号.self.trigger.emit()def handle_trigger(self):# 显示插槽已被调用.打印收到触发信号"

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'

解决方案

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"

这篇关于PyQt5 信号和插槽“QObject 没有属性"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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