PyQt5聚焦输入/输出事件

2024-09-27 09:28:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我说得对吗

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

…在第5季度不起作用?在

我试图理解this但没有成功。我将非常感谢一个简短的例子,如何在许多QLineEdit失去注意力时捕捉事件。在


Tags: self功能signalconnect事件qt5季度qtcore
1条回答
网友
1楼 · 发布于 2024-09-27 09:28:58

这里的问题是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信号为例,可以使用如下所示:

^{pr2}$

这将把self.myProcedure函数连接到textEdited信号。目标函数需要接受事件输出,例如:

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()和{}事件如下:

self.an_event.connect( self.an_event_handler )
self.a_number.connect( self.a_number_handler )

self.an_event.emit()   # Send the event and nothing else.
self.a_number.emit(1)  # Send the event an an int.

您发布的链接给出了more information on custom events、信号命名和新语法重载。在

相关问题 更多 >

    热门问题