An event for focus changed?

2019-04-15 03:52发布

问题:

I'm porting my Visual Basic 6 program to PyQt.

I need to call a function to set some widget enable/disable all the time, I don't want to call a function too many times, so I found a event, when the focus is changed from a widget to another widget, I can call my widget manager function.

I'm looking for the same thing in PyQt but without success. Any idea?

回答1:

Signal QApplication::focusChanged(QWidget * old, QWidget * now) is what you want.



回答2:

Not sure whether you are talking about the widget's window gaining/losing focus or a widget embedded in another gaining/losing keyboard focus, but here's for both situations

class MyWidget(QtGui.QWidget):

    def __init__(self, parent = None):
        super(MyWidget, self).__init__(parent)
        self.installEventFilter(self)

    def eventFilter(self, object, event):
        if event.type() == QtCore.QEvent.WindowActivate:
            print "widget window has gained focus"
        elif event.type()== QtCore.QEvent.WindowDeactivate:
            print "widget window has lost focus"
        elif event.type()== QtCore.QEvent.FocusIn:
            print "widget has gained keyboard focus"
        elif event.type()== QtCore.QEvent.FocusOut:
            print "widget has lost keyboard focus"


        return False