我是第一次使用 Python 3.4 和 Qt 5。这很简单,我可以理解我需要的大部分功能。但是(总是有“但是”)我不明白如何使用 focusOut
/clearFocus
/focusIn
事件。
我的老方法是对的吗:
QObject.connect(self.someWidget, QtCore.SIGNAL('focusOutEvent()'), self.myProcedure)
...在 Qt5 中不起作用?
我试图理解this不成功。我将非常感谢一个简短的示例,如何在许多 QLineEdit
中的一些失去焦点时捕获事件。
最佳答案
这里的问题是 focusInEvent
/clearFocus
/focusOutEvent
不是信号,它们是事件处理程序。例如,参见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 中,信号本身的语法更简单。以 QLineEdit 中的 textEdited
信号为例,您可以按如下方式使用它:
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()
和 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.
您发布的链接给出 more information on custom signals ,使用新语法进行信号命名和重载。
关于python - PyQt5 focusIN/Out 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28793440/