code: def eventFilter(self, widget, event):
          
          if ((event.type() == QEvent.MouseButtonPress and
                   not self.geometry().contains(event.globalPos())) or
                  (event.type() == QEvent.KeyPress and
                   event.key() == Qt.Key_Escape)):
              # Exits editing
              self.hide()
              self.setFocus(False)
              return True
  
          # Event is not interessant, raise to parent
          return QLineEdit.eventFilter(self, widget, event)
docs: Catch clicks outside the object and ESC key press.