这里的问题是focusInEvent
/clearFocus
/focusOutEvent
are not信号,它们是事件处理程序。参见示例here。如果您想捕获这些事件,您将需要在对象上重新实现事件处理程序,例如通过子类化 QLineEdit。
class MyQLineEdit(QLineEdit):
def focusInEvent(self, e):
# Do something with the event here
super(MyQLineEdit, self).focusInEvent(e) # Do the default action on the parent class QLineEdit
在 PyQt5 中,信号本身的语法更简单。以textEdited
来自 QLineEdit 的信号,您可以按如下方式使用它:
self.someWidget.textEdited.connect( self.myProcedure )
这将连接textEdited
向你的信号self.myProcedure
方法。目标方法需要接受信号输出,例如:
void textEdited ( const QString & text )
所以你可以定义你的self.myProcedure
在您的班级中,如下所示,它将收到QString
由该信号发送。
def myProcedure(self, t):
# Do something with the QString (text) object here
您还可以定义自定义信号,如下所示:
from PyQt5.QtCore import QObject, pyqtSignal
class Foo(QObject):
an_event = pyqtSignal()
a_number = pyqtSignal(int)
在每种情况下pyqtSignal
用于定义一个属性Foo
您可以像任何其他信号一样连接到该类。例如,为了处理上述问题,我们可以创建:
def an_event_handler(self):
# We receive nothing here
def a_number_handler(self, i):
# We receive the int
那么你可以connect()
and emit()
信号如下:
self.an_event.connect( self.an_event_handler )
self.a_number.connect( self.a_number_handler )
self.an_event.emit() # Send the signal and nothing else.
self.a_number.emit(1) # Send the signal wih an int.
您发布的链接给出了有关自定义信号的更多信息,使用新语法进行信号命名和重载。