qt.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import sys
  2. import os
  3. from IPython.external.qt_for_kernel import QtCore, QtGui
  4. # If we create a QApplication, keep a reference to it so that it doesn't get
  5. # garbage collected.
  6. _appref = None
  7. _already_warned = False
  8. def inputhook(context):
  9. global _appref
  10. app = QtCore.QCoreApplication.instance()
  11. if not app:
  12. if sys.platform == 'linux':
  13. if not os.environ.get('DISPLAY') \
  14. and not os.environ.get('WAYLAND_DISPLAY'):
  15. import warnings
  16. global _already_warned
  17. if not _already_warned:
  18. _already_warned = True
  19. warnings.warn(
  20. 'The DISPLAY or WAYLAND_DISPLAY enviroment variable is '
  21. 'not set or empty and Qt5 requires this enviroment '
  22. 'variable. Deactivate Qt5 code.'
  23. )
  24. return
  25. _appref = app = QtGui.QApplication([" "])
  26. event_loop = QtCore.QEventLoop(app)
  27. if sys.platform == 'win32':
  28. # The QSocketNotifier method doesn't appear to work on Windows.
  29. # Use polling instead.
  30. timer = QtCore.QTimer()
  31. timer.timeout.connect(event_loop.quit)
  32. while not context.input_is_ready():
  33. timer.start(50) # 50 ms
  34. event_loop.exec_()
  35. timer.stop()
  36. else:
  37. # On POSIX platforms, we can use a file descriptor to quit the event
  38. # loop when there is input ready to read.
  39. notifier = QtCore.QSocketNotifier(context.fileno(),
  40. QtCore.QSocketNotifier.Read)
  41. # connect the callback we care about before we turn it on
  42. notifier.activated.connect(event_loop.exit)
  43. notifier.setEnabled(True)
  44. # only start the event loop we are not already flipped
  45. if not context.input_is_ready():
  46. event_loop.exec_()