首页 > 编程 > Python > 正文

pyqt5自定义信号实例解析

2020-02-22 23:04:51
字体:
来源:转载
供稿:网友

本文研究的主要是pyqt5自定义信号实例解析的相关内容,具体介绍如下。

PyQt5已经自动定义了很多QT内建的信号。但是在实际的使用中为了灵活使用信号与槽机制,我们可以根据需要自定义signal。可以使用pyqtSignal()方法定义新的信号,新的信号作为类的属性。

自定义signal说明:

pyqtSignal()方法原型(PyQt官网的定义):

PyQt5.QtCore.pyqtSignal(types[, name[, revision=0[, arguments=[]]]])
Create one or more overloaded unbound signals as a class attribute.

Parameters:
types – the types that define the C++ signature of the signal. Each type may be a Python type object or a string that is the name of a C++ type. Alternatively each may be a sequence of type arguments. In this case each sequence defines the signature of a different signal overload. The first overload will be the default.

name – the name of the signal. If it is omitted then the name of the class attribute is used. This may only be given as a keyword argument.

revision – the revision of the signal that is exported to QML. This may only be given as a keyword argument.

arguments – the sequence of the names of the signal's arguments that is exported to QML. This may only be given as a keyword argument.
Return type: an unbound signal

新的信号应该定义在QObject的子类中。新的信号必须作为定义类的一部分,不允许将信号作为类的属性在类定义之后通过动态的方式进行添加。通过这种方式新的信号才能自动的添加到QMetaObject类中。这就意味这新定义的信号将会出现在Qt Designer,并且可以通过QMetaObject API实现内省。

通过下面的例子,了解一下关于signal的定义:

from PyQt5.QtCore import QObject, pyqtSignalclass NewSignal(QObject):  # 定义了一个“closed”信号,该信号没有参数据  closed= pyqtSignal()  # 定义了一个"range_changed"信号,该信号有两个int类型的参数  range_changed = pyqtSignal(int, int, name='rangeChanged')

自定义信号的发射,通过emit()方法类实现,具体参见该函数的原型:

emit(*args)
Parameters: args – the optional sequence of arguments to pass to any connected slots.

通过下面的例子,了解一下关于emit()的使用:

from PyQt5.QtCore import QObject, pyqtSignalclass NewSignal(QObject):  # 一个valueChanged的信号,该信号没有参数.  valueChanged = pyqtSignal()  def connect_and_emit_valueChanged(self):    # 绑定信号和槽函数    self.valueChanged.connect(self.handle_valueChanged)    # 发射信号.    self.trigger.emit()  def handle_valueChanged(self):    print("trigger signal received")

示例说明:

自定义信号的一般流程如下:

1、定义信号
2、定义槽函数

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表