Search code examples
pythonpyqt5

Qt event for focus changed with tab key


I have a UI that I would like to implement a form of auto-fill for. I have implemented this by using an event filter to populate the QLineEdit when it's given focus based on the previously focused QLineEdit.

The issue is that I only want this autofill to occur only when the user is using the tab key to cycle through the form. If they are manually clicking around then the autofill will likely be a hindrance.

def eventFilter(self, selected_input, event):
    if event.type() == QEvent.FocusIn:
        if (self.previous_input is not None
            #and selected_via_tab_key
            and selected_input.text() == ""):
            new_value = int(self.previous_input.text()) + 1
            selected_input.setText(str(new_value))
        self.previous_input = selected_input
    return False

Is there any way to detect how the focus was changed within this event, or another event I could monitor for just a tab focus change?


Solution

  • The QFocusEvent event has a reason method, it returns a FocusReason.

    You can compare it to the predefined enumeration values like FocusReason.MouseFocusReason or FocusReason.TabFocusReason to determine how the line edit received focus.

    Links to original Qt documentation: