在 Q Line Edit PYQT 中添加 Focus In 和 Focus out 事件

adding Focus In and Focus out events in Q Line Edit PYQT

我想在 QLine Edit 小部件上设置 FocusIn 和 Focusout 事件,但无法这样做。我知道我非常接近解决方案但无法获得确切的解决方案。我的代码:-

from PyQt4.QtGui import *
url = QtGui.QLineEdit("Please enter URL", w)
url.setFixedWidth(800)
url.move(500,0)
url.focusInEvent(QFocusEvent)

if url.gotFocus():
 print "got focus"
elif url.lostFocus():
 print "lost focus"   

请帮助我调试问题。

您可能应该查看 focusInEvent 方法的文档

This event handler can be reimplemented in a subclass to receive keyboard focus events (focus received) for the widget.

它意味着在子类中被覆盖。你不要直接调用它,事件系统会在 focusIn 事件发生时自动调用它。你需要做这样的事情。

class MyLineEdit(QtGui.QLineEdit):

    def focusInEvent(self, event):
        print 'focus in event'
        # do custom stuff
        super(MyLineEdit, self).focusInEvent(event)

gotFocuslostFocus 甚至都不是实际方法。