PyQt5 focusIN/Out 事件

2023-12-14

我是第一次使用 Python 3.4 和 Qt 5。这很简单,我可以理解我需要的大部分功能。但是(总是有“但是”)我不明白如何使用focusOut/clearFocus/focusIn事件。

我的老方法是对的吗:

QObject.connect(self.someWidget, QtCore.SIGNAL('focusOutEvent()'), self.myProcedure)

...在 Qt5 中不起作用?

我试着去理解this不成功。我将非常感谢一个简短的例子,当例如许多事件中的一些事件时如何捕获事件QLineEdit失去了焦点。


这里的问题是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.

您发布的链接给出了有关自定义信号的更多信息,使用新语法进行信号命名和重载。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PyQt5 focusIN/Out 事件 的相关文章

随机推荐