combobox steal keyboard from main window in pyqt

797 views Asked by At

I'm writing a small pyqt program. I want the main window to to react to arrow movement. I added an event to my MainGui class, keyPressEvent, that handle this. The event work fine as long as I don't press certain buttons such as Key_Up or Key_Down are directed to my (currently only) QComboBox and not to my mainGui. I tried to give the focus to mainGui after each paintEvent but then I need to double click on buttons/comboBox.

Then I tried to use the MousePressEvent to check if a certain element is under the mouse. This work fine with the comboBox, but not with the button.

So, how can I direct key events to the mainGui or give the focus to QButtons?

1

There are 1 answers

0
Yotam On

I used eventFilter to identify when the mouse enter the QPushButton and give it focus:

def eventFilter(self,source,event):
  if event.type() == QtCore.QEvent.HoverMove:
     if self.execButton.underMouse():
        self.execButton.setFocus()
        self.keepFocus=False
     else :
        self.keepFocus=True

keepFocus is a flag I initialized in the __init__ function of the class. I added this part at the paintEvent function

    if self.keepFocus:
        self.setFocus()
    else:
        self.keepFocus = True

Now, I keep the focus at the MainGui and I only give it to the button when the mouse hove over it. If I do another action (like pressing a mouse button or a keyboard key) the focus is given back to the MainGui. This will create some buggy filling (For example, I need to press twice a keyboard key before the first response) but this is workable.