Search code examples
python-3.xqtpyside2focusout

Python 3.x / PySide2 / focusOutEvent for main window isn't firing


I tried to get a notification whenever my app looses focus. But simply reimplementing "focusOutEvent" isn't working.

I have found this as a workaround:

PyQt window focus events not called

But I'm still interested if there is a way to simply use "focusOutEvent" somehow. Here's a small example app that doesn't do anything for me in regards to focusevents.

#!/usr/bin/python3

from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
import sys

class MainWindow(QMainWindow):
  def __init__(self):
      super().__init__()
      print("Window created")
  def focusOutEvent(self, e):
      print(e)
      print("window lost focus")

def main():
  app = QApplication(sys.argv)
  window = MainWindow()
  window.show()
  app.exec_()

if __name__ == '__main__':
    main()

Solution

  • What you're looking for called QEvent.WindowActivate and QEvent.WindowDeactivate

    from PySide2 import QtWidgets
    from PySide2 import QtCore
    
    class Window(QtWidgets.QMainWindow):
    
        def event(self, event):
            if event.type() == QtCore.QEvent.WindowActivate:
                print('WindowActivate')
            elif event.type() == QtCore.QEvent.WindowDeactivate:
                print('WindowDeactivate')
            return super().event(event)
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication([])
        window = Window()
        window.show()
        app.exec_()