某些情况下,需要通过编程产生信号。例如,填表完成按下回车键时,需要模拟按下”OK“按钮。实现该功能的函数为QObject类的emit()。
格式为:
emit(*args)
args--传递到任何连接槽的的可选序列传参数;
模拟按钮动作的代码:
button.clicked.emit()
在调用emit()时,信号和槽可以传递参数。例如:
button.clicked[bool].emit(False)
button.clicked["bool"].emit(False)
PyQt5已经自动定义了很多QT内建的信号。但是在实际的使用中为了灵活使用信号与槽机制,我们可以根据需要自定义signal。可以使用pyqtSignal()方法定义新的信号,新的信号作为类的属性。pyqtSignal()方法原型:
PyQt5.QtCore.pyqtSignal(types[, name[, revision=0[, arguments=[]]]])
函数参数:
types – the types that define the C++ signature of the signal. Each type may be a Python typeobject 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
一个信号可以有多个重载的版本。
通过情况下,默认的信号名与类的属性相同。但也可通过name参数生成一个特定的名称:
mysignal = QtCore.pyqtSignal(int, name = 'mySignal')
下面的例子将创建两个按钮。第一个按钮按下时产生两个信号:
1.模拟按钮2被按下
2.产生一个屏幕位置的信号
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtWidgets
class MyWindow(QtWidgets.QWidget):
mysignal = QtCore.pyqtSignal(int, int)
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setWindowTitle("编程产生信号")
self.resize(300, 100)
self.button1 = QtWidgets.QPushButton("点击按钮1")
self.button2 = QtWidgets.QPushButton("按钮 2")
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.button1)
vbox.addWidget(self.button2)
self.setLayout(vbox)
self.button1.clicked.connect(self.on_clicked_button1)
self.button2.clicked.connect(self.on_clicked_button2)
self.mysignal.connect(self.on_mysignal)
def on_clicked_button1(self):
print("按下按钮1")
# 触发信号
self.button2.clicked[bool].emit(False)
self.mysignal.emit(10, 20)
def on_clicked_button2(self):
print("按下按钮2")
def on_mysignal(self, x, y):
print("处理自定义信号mysignal()")
print("x =", x, "y =", y)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
除了指定接收特定类型的信号参数外,还可以指定成Qtcore.QVariant类型。在这种情况下,可传送任何类型的数据:
mysignal = QtCore.pyqtSignal(QtCore.QVariant)
. . .
self.mysignal.emit(20)
self.mysignal.emit("你好!")
self.mysignal.emit([1, "2"])